0

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.

DL33
  • 194
  • 8
  • 1
    `int a; a += b;` is definitely UB. – cigien May 19 '20 at 23:26
  • 1
    *"the thing actually causes UB with uninit variables is an lvalue to rvalue cast that happens implicitly"* can you elaborate? – François Andrieux May 19 '20 at 23:26
  • Further, "I have absolutely no clue how postfix operators save the 'value' of the variable without copying" - they don't; thus the point of why postfix is expensive and should only be used when you actually *need* the value-prior in the first place. – WhozCraig May 19 '20 at 23:29
  • If you think of the `+=` operator as simply being defined as `int &operator+=(int &l, int r) { return l = l + r }`, I think it becomes clear. The evaluation of `l` is simply hidden inside "library code." – HTNW May 19 '20 at 23:31
  • Well, looks like Clang AST lies from time to time... – DL33 May 19 '20 at 23:39
  • That's assuming that you are interpreting the AST correctly. – cigien May 19 '20 at 23:41

1 Answers1

2

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.

eerorika
  • 232,697
  • 12
  • 197
  • 326