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;
}
出力-
2 5
-1076828408 -1076828404
2 5
-1076828408 -1076828404
5 2
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;
}
コンパイル情報
prog.c:3:15: エラー: 「&」の前に「;」、「,」、または「)」が必要です トークン
void swap(int &a, int &b){
^
prog.c: 関数 'main' 内:
prog.c:15:4: 警告: フォーマット '%d' はタイプ 'int' の引数を想定していますが、引数 2 のタイプは 'int *' です [-Wformat=]
printf("%d %d\n", &a, &b);
^
prog.c:15:4: 警告: フォーマット '%d' はタイプ 'int' の引数を想定していますが、引数 3 のタイプは 'int *' です [-Wformat=]
prog.c:17:2: 警告: 関数 'swap' の暗黙の宣言 [-Wimplicit-function-declaration] swap(a,b); ^
call be reference として C++ で機能するのに、C では機能しないのはなぜですか?
int &a; とは 平均?