[英]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);
}
在上述c程序中,它不起作用,但在c ++中相同,即
#include<iostream>
void sq(int &b) {
b=b+12;
}
int main() {
int a=5;
sq(a);
std::cout<<a;
}
在c ++中傳遞變量的方式是否有所不同? 為什么它在c ++中起作用? 以上代碼在c ++中是通過引用傳遞的?
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
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.