Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

assignment operation confusion

What is the output of the following code:

int main() {
  int k = (k = 2) + (k = 3) + (k = 5);
  printf("%d", k);
}

It does not give any error, why? I think it should give error because the assignment operations are on the same line as the definition of k.

What I mean is int i = i; cannot compile. But it compiles. Why? What will be the output and why?

like image 225
Renato de Castro Avatar asked Apr 08 '26 19:04

Renato de Castro


1 Answers

int i = i compiles because 3.3.1/1 (C++03) says

The point of declaration for a name is immediately after its complete declarator and before its initializer

So i is initialized with its own indeterminate value.

However the code invokes Undefined Behaviour because k is being modified more than once between two sequence points. Read this FAQ on Undefined Behaviour and Sequence Points

like image 143
Prasoon Saurav Avatar answered Apr 10 '26 11:04

Prasoon Saurav



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!