0
#include<stdio.h>

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

void main() {

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

}

在上面的 c 程序中,它不起作用,但在 c++ 中同样有效,即

#include<iostream>

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

 int main() {

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

}

变量在 c++ 中的传递方式有什么不同吗?为什么它在 c++ 中工作?上面的代码是在 c++ 中通过引用传递的吗?

4

1 回答 1

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
}
于 2012-08-29T22:08:47.417 回答