Search code examples
cundefined-behavior

Is it UB to use zero multiplied uninitialized variable?


Is there UB in the following code?

#include <stdio.h>

int main(void)
{
    int x;
    printf("%d", 0*x);
    return 0;
}

Here, the variable x was not initialized, but was multiplied by 0 and the result was passed to printf. Mathematically, the result passed to printf should be 0, but I guess that in c language this invokes UB. If the variable was not multiplied by 0 it is clearly UB but I am not sure is it UB in this particular case.

Ideone link


Solution

  • Yes, it's UB.

    A conforming compiler may not do any optimization and run into a trap representation in x.
    Some implementations may reserve some bits for special values, including trap representations.