Why is initialization of a new variable by itself valid? [duplicate]

It’s syntactically valid, since the variable’s point of declaration comes before its initialiser, and the name is available anywhere after that point. This allows less dodgy initialisations like

void *p = &p;

which legitimately uses the name (but not the value) of the variable being initialised.

It’s behaviourally invalid, since using the value of an uninitialised object gives undefined behaviour. That’s not an error that requires diagnosis (since, in general, it can be difficult or impossible to analyse the program flow to see whether an object has been initialised), but as you note, many compilers will give a warning for straightforward cases like this.

Leave a Comment