简体   繁体   中英

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

#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++ ?? whydoes it work in c++ ? is above code pass by reference in c++ ?

C and C++ are different languages. C does not have references.

If you want reference semantics in C, then use pointers:

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM