Changing the value of one function to another

Time:2021-4-30

A variable in one function, such as int a, cannot be changed in another function.
for example

#include<stdio.h>
void change(double in);
int main(void)
{
    double a = 0.0;
    change(a);
    printf("%lf", a);
}
void change(double in)
{
    in = 2.0;
}

The output is
Changing the value of one function to another

The way to change it

Pointer

If you want to change the value of another function in one function, you can pass the pointer, but not the variable, because the variables in these two functions are placed in different locations in memory. You can’t change the value of another function in one function. If you want to change the value, you can only change the value in its memory directly

#include<stdio.h>
void change(double* in);
int main(void)
{
    double a = 0.0;
    change(&a);
    printf("%lf", a);
}
void change(double* in)
{
    *in = 2.0;
}

The output is
Changing the value of one function to another
Successfully changed the value of a variable in one function to another.
That’s why the scanf function uses&

quote

By using the reference symbol & here & is not the address symbol, which means to refer to the passed parameter. The reference means to take an alias for the passed parameter, and the operation on the formal parameter is the operation on the passed parameter.

#include<iostream>
using namespace std;
int change(int& in)
{
    in = 5;
    return 0;
}
int main(void)
{
    int a = 0;
    change(a);
    cout << a;
    return 0;
}