简体   繁体   中英

Code for swapping integers works in C++ but not C

I have this function that swaps integers passed by reference, it works fine in C++ but it does not work in C.

#include <stdio.h>

void swap(int & x, int & y) 
{ 
    int z = x; 
    x = y; 
    y = z; 
}

int main() 
{
    int a = 0, b = 1;
    swap(a, b);
    printf("a is now %d\n", a);
    printf("b is now %d\n", b);
}

Why doesn't it work in C?

C and C++ have some overlap, but they are two different languages. C has no references.

Even the claim that C++ is a superset of C is outdated. C has evolved since C++ started as "C with classes" and not all features added to C are also incorporated into C++. Hence it should not be too surprising that what works in one does not necessarily work in the other.

These are two different languages, you can't expect that something that works in one can work in the other, passing by reference is not possible in C.

You can, however, pass by pointer:

#include <stdio.h>

void swap(int* const x, int* const y)  
{ 
    int z = *x; 
    *x = *y; 
    *y = z; 
}  

int main() 
{
    int a = 0, b = 1;
    swap(&a, &b);
    printf("a is now %d\n", a);
    printf("b is now %d\n", b);
}

This line declares 2 parameters as references :

void swap(int & x, int & y) 

The C language does not have references.

If you attempt to compile this with a C compiler, you should get:

error: expected ‘;’, ‘,’ or ‘)’ before ‘&’ token

IDEOne link

C does not have references but you can use pointers or make a macro:

#include <stdio.h>
#define swap(X,Y) do {int Z=X; X=Y; Y=Z;} while(0)

int main() 
{
    int a = 0, b = 1;
    swap(a, b);
    printf("a is now %d\n", a);
    printf("b is now %d\n", b);
}

AS in c language to be able to change the actual value for a certain variable you should call it by reference so in this code to be able to change (swape) between variables you should use method of call by address ( here when you finish swape function the copied variables will be removed from the memory and actual variables will stay with the same values )

#include <stdio.h>

void swap(int* x, int* y) 
{ 

    *x=*x^ *y;
     *y=*x ^ *y;
     *x=*x ^ *y;        
}  
int main() 
{
    int a =0, b = 1;
    swap(&a,&b);
    printf("a is now %d\n", a);
    printf("b is now %d\n", b);
}

note: swap(a,b); is wrong in c language you should pass these variables by address to be able to swape their values as swape function return void

another solution

#include <stdio.h>

void swap(int* x, int*  y)  
{   int z = *x ;
     *x = *y ;
      *y=z;
}  

int main() 
{
    int a = 0, b = 1;
    swap(&a, &b);
    printf("a is now %d\n", a);
    printf("b is now %d\n", b);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM