Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If the value of an uninitialized variable shouldn't affect the value of an expression, is it still UB?

This is a follow-on from a discussion, which I think deserves a question of its own.

Basically, is the result of this undefined?

int x;
int y = 1 || x;

There are two "common-sense" arguments here:

  1. Mathematically speaking, no matter what the value of x, the value of y should be 1.
  2. Because of short-circuiting, x is never evaluated anyway.

But the counterargument is that we have an expression that involves an uninitialized variable, so all bets are off (in theory).

More generally, if the value of an uninitialized variable can't possibly affect the result of an expression, is it "safe"? e.g.:

int x;
int y = x - x;

Usual disclaimer: Of course, I'm not advocating ever writing code like this.

like image 810
Oliver Charlesworth Avatar asked Sep 01 '11 11:09

Oliver Charlesworth


People also ask

What happens if you don't initialize a variable?

Initializing a variable means specifying an initial value to assign to it (i.e., before it is used at all). Notice that a variable that is not initialized does not have a defined value, hence it cannot be used until it is assigned such a value.

What is the value of an uninitialized variable?

An uninitialized variable has an undefined value, often corresponding to the data that was already in the particular memory location that the variable is using. This can lead to errors that are very hard to detect since the variable's value is effectively random, different values cause different errors or none at all.

What happens if we use an uninitialized variable where it is declared but no initial value is given?

An uninitialized variable is a variable that has not been given a value by the program (generally through initialization or assignment). Using the value stored in an uninitialized variable will result in undefined behavior.

What is an uninitialized variable SET TO LET result What is result?

In computing, an uninitialized variable is a variable that is declared but is not set to a definite known value before it is used. It will have some value, but not a predictable one. As such, it is a programming error and a common source of bugs in software.


1 Answers

In C, it is undefined behavior to use the value of an object with automatic storage duration while it is indeterminate. (J.2, informative) but it's OK for variables with automatic storage duration to hold an indeterminate value.

An expression can only have its value used if it is evaluated and according to 6.5.12 (Logical OR operator) the second operand is not evaluated (let alone have its value used) if the first operand compares unequal to 0.

like image 134
CB Bailey Avatar answered Sep 21 '22 02:09

CB Bailey