Understanding the difference when passing values by reference in C++ vs in C

Hi,

I was practicing values by reference in C++, which I now understand but I came across something that is bothering me. I thout that since C++ is a subset of C stuff like passing values by reference would be the same in either language but to my surprise it is not.

For instance, I had this C++ code that works well

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
using namespace std;

void myFunction(int &num)
{
    num = num +2;
}

int main()
{
    int myNum =1;
    myFunction(myNum);
    
   cout << "The value of myNum is :" << myNum << endl; 
   
   return 0;
}
// output: The value of myNum is :3 



... but when I tried to reuse the same code in C it didn't work. I got the following error

main.c:4:21: error: expected ';', ',' or ')' before '&' token
void myFunction(int &num)


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <stdio.h>
#include <string.h>

void myFunction(int &num)
{
    num = num +2;
}

int main()
{
    int myNum =1;
    myFunction(myNum);

   printf ( "The value of myNum is : %i", myNum);
   
   return 0;
}

... then I modified my code, this time it worked but the output is not what I was expecting

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <stdio.h>
#include <string.h>

void myFunction(int *num)
{
    num = num +2;
}

int main()
{
    int myNum =1;
    myFunction(&myNum);

   printf ( "The value of myNum is : %i", myNum);
   
   return 0;
} 

// output: The value of myNum is : 1 


Can someone explain why it doesnt work when compile with a C compiler but works with a C++ compiler?

Thanks

why it doesnt work when compile with a C compiler but works with a C++ compiler?

C and C++ are different languages, you can't expect a program written in one language to compile with the other language's compiler (although there are quite a few C programs that can be compiled with a C++ compiler, and most of the time they would even work the same - that portability was a big reason C++ took off)

In particular, C has no language-level support for pass-by-reference semantics. It can emulate that through passing a pointer (by value) and dereferencing it each time an access the "by-reference" parameter is needed.
Last edited on
This function:
1
2
3
4
void myFunction(int *num)
{
    num = num +2;
}

should be like this:
1
2
3
4
void myFunction(int *num)
{
    *num = *num + 2;
}
@Cubbi (3260)

This answers my question:
In particular, C has no language-level support for pass-by-reference semantics. It can emulate that through passing a pointer (by value) and dereferencing it each time an access the "by-reference" parameter is needed.


I just thought that passing by reference was a feature that came from the C language and inherited by C++.
Last edited on
Thanks you all for your help!
Topic archived. No new replies allowed.