[英]pass by reference in c++/c
#include<stdio.h>
void sq(int &b) {
b=b+12;
}
void main() {
int a=5;
sq(a);
printf("%d",a);
}
In the above c program, it does not work but the same works in c++ ie 在上述c程序中,它不起作用,但在c ++中相同,即
#include<iostream>
void sq(int &b) {
b=b+12;
}
int main() {
int a=5;
sq(a);
std::cout<<a;
}
Is there a difference in how the variable is passed in c++ ?? 在c ++中传递变量的方式是否有所不同? whydoes it work in c++ ?
为什么它在c ++中起作用? is above code pass by reference in c++ ?
以上代码在c ++中是通过引用传递的?
C and C++ are different languages. C和C ++是不同的语言。 C does not have references.
C没有参考。
If you want reference semantics in C, then use pointers: 如果要在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
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.