2012-08-29 37 views
0
#include<stdio.h> 

void sq(int &b) { 
    b=b+12; 
} 

void main() { 

int a=5; 
sq(a); 
printf("%d",a); 

} 

在上面的C程序中,這是行不通的,但在C++中即通在C基準++/C

#include<iostream> 

void sq(int &b) { 
    b=b+12; 
} 

int main() { 

int a=5; 
sq(a); 
std::cout<<a; 

} 

相同的工作原理是那裏的變量如何在C通過差異++? ?它在C++中工作嗎? 是上面的代碼在C++中通過引用傳遞?

+1

不像C++,C沒有引用,只有指針。 –

+1

你是什麼意思的「它不工作」?你的意思是你沒有看到17打印出來,或者它不能編譯? –

+0

你是什麼意思的「不起作用」?代碼是用C++編譯的,而不是用C編譯的?還是它編譯並不輸出你所期望的? –

回答

10

C和C++是不同的語言。 C沒有參考。

如果你想在C基準語義,然後使用指針:

void sq(int * b) {  // Pass by pointer 
    *b = *b + 12;  // Dereference the pointer to get the value 
} 

int main() {   // Both languages require a return type of int 
    int a = 5; 
    sq(&a);    // Pass a pointer to a 
    printf("%d\n", a); 
    return 0;   // C used to require this, while C++ doesn't 
         //  if you're compiling as C99, you can leave it out 
} 
+0

自C99以來,C不需要'return 0;'。 –

+2

@LucDanton:足夠公平,我從1999年起就沒有真正使用過C語言。 –

+0

在c中傳遞參數的兩種方式是1)按值傳遞,2)通過引用(指針)傳遞對嗎? – hunterr986