DL33
DL33

Reputation: 204

Is using compound assignment operator (+=, ...) on uninitialized variable NOT a UB in C++?

I am trying to create a simple tool to detect the use of uninitialized variables based on Clang AST. What I know is that the thing actually causes UB with uninit variables is an lvalue to rvalue cast that happens implicitly.

Now what I noticed while examining the AST of a basic example program is that all compound assignment operators do not cause any such cast node to appear! Does this imply that no UB takes place?

int a;
int b = 10;
b += a; // this line is obviously UB...
a += b; // ... but is this one ok?

// Note: no ImplicitCastExpr of LvalueToRvalue type in AST !

That is also true for postfix / prefix increment / decrement operators (in particular, I have absolutely no clue how postfix operators save the 'value' of the variable without copying).

I managed to find some info about increment operators (Is it legal to increment non-initialized variable? - only one reference, unfortunately), but now struggle with comp. assignments. If possible, I'd love to know in particular what happens to increment as well.

Upvotes: 0

Views: 216

Answers (1)

eerorika
eerorika

Reputation: 238351

Is using compound assignment operator (+=, …) on uninitialized variable NOT a UB in C++?

No, it is UB (except for in cases where standard says it's not).

Standard quotes (from latest draft):

[expr.ass] The behavior of an expression of the form E1 op= E2 is equivalent to E1 = E1 op E2 except that E1 is evaluated only once.

So, we know that left hand operand is evaluated. And we also know that the value is used in the operation.

[basic.indet] If an indeterminate value is produced by an evaluation, the behavior is undefined ...

There you have it.

Upvotes: 2

Related Questions