C++ – C Variable Scope Specific Question

argument-passingcparameter-passingpass-by-referencescope

Here is a particular scenario that I have been unclear about (in terms of scope) for a long time.

consider the code

#include <stdio.h>


typedef struct _t_t{
    int x;
    int y;
} t_t;

typedef struct _s_t{
    int a;
    int b;
    t_t t;
}s_t;

void test(s_t & s){
    t_t x = {502, 100};
    s.t = x;
}


int main(){
    s_t s; 
    test(s);

    printf("value is %d, %d\n", s.t.x, s.t.y);
    return 0;
}

the output is

value is 502, 100

What is a bit confusing to me is the following. The declaration

t_t x

is declared in the scope of the function test. So from what I have read about C programming, it should be garbage out of this scope. Yet it returns a correct result. Is it because the "=" on the line
s.t = x;
copies the values of x into s.t?

edit—

after some experimentation

#include <stdio.h>


typedef struct _t_t{
    int x;
    int y;
} t_t;

typedef struct _s_t{
    int a;
    int b;
    t_t t;
}s_t;

void test(s_t & s){
    t_t x = {502, 100};
    t_t * pt = &(s.t);
    pt = &x;
}


int main(){
    s_t s; 
    test(s);

    printf("value is %d, %d\n", s.t.x, s.t.y);
    return 0;
}

actually outputs

value is 134513915, 7446516

as expected.

Best Answer

Is it because the "=" on the line s.t = x; copies the values of x into s.t?

Yes.

By the way, this is C++. You've passed the "s" local to main as a reference to the function, which modifies it. Because it's a reference, and not a copy, it affects the caller's "s".