Here's something I don't understand. Maybe someone can shed some light on it.
I know that the standard method for data manipulation is passing a reference to a function and changing the data in the function. Like this:
#include <stdio.h>
#include <stdlib.h>
void function2( float *param) {
printf("I've received value %f\n", *param);
(*param)++;
}
int main(void) {
float variable = 111;
function2(&variable);
printf("variable %f\n", variable);
return 0;
}
When calling function2 with (&variable) I expect that the function can change the data. So far no questions.
But why does this work as well?
#include <stdio.h>
#include <stdlib.h>
void function2( float ¶m) {
printf("I've received value %f\n", param);
(param)++;
}
int main(void) {
float variable = 111;
function2(variable);
printf("variable %f\n", variable);
return 0;
}
In my understanding, when calling function2(variable) a copy of the value of "variable" is passed to the function. But nevertheless the value of "variable" has changed after the function call.
When reading a code like this I would never expect the data of "variable" to change, no matter what happens inside the function.
This declaration of the parameter
void function2( float ¶m) {
is incorrect. In C there is no reference. Such a function declaration will be valid in C++, where references exist.
In C++ when the function is called like
function2(variable);
neither copy of the variable is created. The function refers to the original variable declared in main.