The code in C++ - Ideone
#include <stdio.h>
using namespace std;
void swap(int &a, int &b){
printf("%d %d\n", a, b);
printf("%d %d\n", &a, &b);
int temp=a;
a=b;
b=temp;
}
int main(void) {
int a=2, b=5;
printf("%d %d\n", a, b);
printf("%d %d\n", &a, &b);
swap(a,b);
printf("%d %d\n", a, b);
return 0;
}
OUTPUT-
2 5
-1076828408 -1076828404
2 5
-1076828408 -1076828404
5 2
The code in C - Ideone
#include <stdio.h>
void swap(int &a, int &b){
printf("%d %d\n", a, b);
printf("%d %d\n", &a, &b);
int temp=a;
a=b;
b=temp;
}
int main(void) {
int a=2, b=5;
printf("%d %d\n", a, b);
printf("%d %d\n", &a, &b);
swap(a,b);
printf("%d %d\n", a, b);
return 0;
}
compilation info
prog.c:3:15: error: expected ‘;’, ‘,’ or ‘)’ before ‘&’ token
void swap(int &a, int &b){
^
prog.c: In function ‘main’:
prog.c:15:4: warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘int *’ [-Wformat=]
printf("%d %d\n", &a, &b);
^
prog.c:15:4: warning: format ‘%d’ expects argument of type ‘int’, but argument 3 has type ‘int *’ [-Wformat=]
prog.c:17:2: warning: implicit declaration of function ‘swap’ [-Wimplicit-function-declaration] swap(a,b); ^
why does it work in C++ as call be reference, but not in C?
What does int &a; mean?