+ 1
Why any parameters value doesn't change.
if we call any function have parameters as array and integer. After execution of function why only array is updated why not integer value Globally.
3 Answers
+ 3
By default, normal parameters like int, char, etc are 'Passed by Value'. This means that before execution, the compiler creates a copy of the variables passed and uses those variables. The original variables, remain unchanged.
But if you need to change the original variable, you need to 'Pass by Reference'. Passing by reference means that now you pass an address of the original variable that is copied into a temp variable, but since the address is same, any changes in temp will be reflected in the original variable as well.
By default, arrays are always passed by reference, as they are nothing but address locations holding particular types.
If your function is of the form :
int my_func ( int arr[], int a);
To make it pass by reference, you just add a & to the variable needed to be changed.
Eg - int my_func( int arr[], int& a);
// Now a will be changed even in main...
+ 1
while passing an array we basically pass the address of the array, hence the values of an array are updated at that address only.
but in the case of integer we pass the value for eg. 3 or 4 and that is stored in function parameter and when this value is updated, its updated for the function parameter whereas the original value passed from the main function is not changed.
P.S. in order to update the value of main function while updating the parameter value, you can either define that variable globally or return that updated value from function.
+ 1
thanks