hunterr986
hunterr986

Reputation: 43

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++ i.e.

#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++ ?

Upvotes: 0

Views: 463

Answers (1)

Mike Seymour
Mike Seymour

Reputation: 254461

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
}

Upvotes: 10

Related Questions