Parameter passing
C provides only pass by value, meaning that the value is copied from the actual parameter into the formal parameter. Therefore, to change the value in the calling function, you must use pointers:
#include void foo(int x, int *y) { x = x + 1; *y = x + (*y + 1); } /* some stuff, then... */ int a = 0, b = 2; foo(a, &b); printf("%d, %d\n", a, b); C++ supports an additional calling convention, called call by reference. Call by reference is essentially "syntactic sugar" for a pointer. Assigning to a call by reference parameter results in a change of the original value. The syntax is as follows:
#include void bar(int x, int &y) { x = x + 1; y = x + y + 1; } // Some stuff, then... int a = 0, b = 2; bar(a, b); cout << a << ", " << b << endl; I have used some other C++ features as well:
- C++ one-line comments: //
- The C++ standard output stream object, cout