Search code examples
cstructbit-fields

Error using unsigned int bit-field struct in C


I am using struct with unsigned int bit-fields perfectly, but suddenly, after duplicating one of them, the compiler is losing its mind (it would seem). Here's my code:

typedef struct myStruct {
    unsigned int myVar:1;
} myStruct; // my compiler requires TWO declarations of the name for typedef

myStruct myNewStructVar;

myNewStructVar.myVar = 0; // throws error that "myNewStructVar" is unknown to the compiler

What gives? Again, I have two versions of this EXACT thing and it works fine.


Solution

  • You can declare the variable as a global outside of function scope, but you can't have a separate line of code to set its value. Setting the value on a separate line is executable code rather than initialization, and is not permitted there.

    If you want to initialize it at the point of declaration, try:

    myStruct myNewStructVar = {0};
    

    This should work where it is now.