Search code examples
cbitwise-operatorsundefined-behaviorxor

Applied XOR operator with an uninitialized variable in C


I'm a little bit confused. As far as I know, if you declare uninitialized variable in C, so its value is indeterminate.

If you don’t initialize an variable that’s defined inside a function, the variable value remain undefined.That means the element takes on whatever value previously resided at that location in memory.

If I applied ^(XOR) operator to uninitialized integer variable itself. Like,

#include <stdio.h>

int main()
{
        int a;
        printf("%d\n", a^a);
}

it's clear that a^a should be zero because the result is zero only when we have two zeroes or two ones. So, I have a question : Is it undefined behaviour?


Solution

  • Yes, this is undefined behaviour.

    Attempt to use a variable with indeterminate value which

    • can have trap representation
    • not have it's address taken

    will cause undefined behavior.