Search code examples
c++structbit-fields

How does this litle program work?


I tried to check QA exercices about C++ and one question drove me crazy !!

typedef struct {
    unsigned int i : 1;
} myStruct;

int main()
{
    myStruct s;
    s.i = 1;
    s.i++;
    cout << s.i;
    return 0;
}

The question said what is the ouput : 0/1/2/3/-1/Seg Error ?

I did check 2 which is a wrong answer :D , so why does the program shows 0 ?


Solution

  • You need to familiarize yourself with bitfields.

    By default int has size of 32 bits(4 bytes). But using the given notation, you can specify how many bits are used for the variable.

    So when you increment the value from 1, it overflows and returns to zero.