0

Say there's a struct

   struct  refresh {
        int     endflag;
   };

and if I refer to refresh.endflag in a function yet I haven't given a value for the endflag, does it get initialized as 0? Thanks in advance.

  • 3
    Where do you define the variable? – dbush Jan 10 '20 at 02:32
  • I just use the refresh.endflag value to compare to something in the main function. But I haven't assigned a value to refresh.endflag at all. So if I make a reference without initializing a value of an int struct member, does it automatically become 0 or does it give me error? – Sangjoon Lee Jan 10 '20 at 02:39
  • It depends on where you defined the variable. Please update your question with a [mcve]. – dbush Jan 10 '20 at 02:40
  • By variable, do you mean the structure member? – Sangjoon Lee Jan 10 '20 at 02:49
  • 1
    The member doesn't exist by itself. It lives in an instance of the struct, for example `struct refresh refresh;`. What you have above only defines the members of the struct, not an instance of it. – dbush Jan 10 '20 at 02:50
  • The instance of the structure is passed in as an argument of the function: struct refresh *refresh. – Sangjoon Lee Jan 10 '20 at 02:56
  • The structure that is passed in as an argument comes from another function, where it is defined like this: struct refresh refresh; – Sangjoon Lee Jan 10 '20 at 03:00
  • 1
    Then the field values are undefined (has a value but cannot be predicted what the exact value is). Read the link for more details. – kaylum Jan 10 '20 at 03:01
  • @SangjoonLee, If variable define inside a function and uninitialized, its value not predictable. It can be initialize with zero or not. leaving this variable uninitialized is undefined behavior. – EsmaeelE Jan 10 '20 at 03:04
  • I see. Thanks a lot! – Sangjoon Lee Jan 10 '20 at 03:05
  • see this link: https://www.geeksforgeeks.org/memory-layout-of-c-program/ – EsmaeelE Jan 10 '20 at 03:06
  • gcc compiler produce warning with -Wall flag when try to leave local variables uninitialized: `untitled.c:98:2: warning: ‘insideFunction.endflag’ is used uninitialized in this function [-Wuninitialized] printf("inside function: %d\n", insideFunction.endflag);` – EsmaeelE Jan 10 '20 at 03:07
  • After all of that its better to be precise and initialize all variables you define. – EsmaeelE Jan 10 '20 at 03:10

0 Answers0