0

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?

Grijesh Chauhan
  • 57,103
  • 20
  • 141
  • 208
xRahul
  • 364
  • 5
  • 18

1 Answers1

4

& used in function definitions like that are called references. They're different from pointers and are not supported in C.

nemasu
  • 426
  • 2
  • 10
  • got it, Thanks for the info. and now I remember studying this a while back.. I stumbled upon it while studying pointers in C and it didn't look like call by value, nor the call by reference we study generally. – xRahul Sep 27 '13 at 13:15