Search code examples
cstructtypedef

C global typedef struct but local initialisation within function, values of struct not reset when function is call more than once


I am currently learning C and am facing some issues with the codes below:

typedef struct{
    string name;
    int age;
    bool tall;
}
person;

max_index =3;

person x_1[max_index];

int main(void)
{
    //lines of code
    while (true)
    {
     function1();
     function2();
     }
}

int function1(void)
{
   person x_2[max_index];
   for (int j=0; j< max_index; j++)
   {
    if (some conditions)
    {
     x_2[j].name = x_1[j].name;
     x_2[j].age = x_1[j].age;
    } 
   }

}
int function2(void)
{
  person x_3[max_index];
  for (int j=0; j< max_index; j++)
  {
   if (some conditions)
    {
      x_3[j].name = x_1[j].name;
      x_3[j].age = x_1[j].age;
    }
   }
}



  1. person struct
  2. a main function that calls function1 and function2 while evaluating certain conditions
  3. function1 and function2 initialize a new person struct separately - x_2 and x_3

Issue: realise that if the main function calls function1 and function2 > once, the values in x_2 and x_3 remains the same as the previous call. My understanding is since x_2 and x_3 exists only within (local) function1 and function2, each call to both the function will "reset" x_2 and x_3? i.e. a new x_2 and x_3 with each call. But that doesn't seems like the case... I am new to C and not sure what exactly is the issue (unable to google)

Update: indeed, printf helped. There were no issues with the code but rather the debugger was showing wrong variable values.


Solution

  • Variables declared at block scope, such as variables local to a function, take on indeterminate values if they are not explicitly initialized. They are not "reset". That means you can't rely on them having any particular value, and the value being read can even change from one access to the next.

    In addition to this, in many cases simply reading a variable whose value is indeterminate can trigger undefined behavior in your program.