Renato de Castro
Renato de Castro

Reputation: 153

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?

Upvotes: 3

Views: 136

Answers (3)

shelman
shelman

Reputation:

Wow, I got 11 too. I think k is getting assigned to 3 twice and then once to 5 for the addition. Making it just int k = (k=2)+(k=3) yields 6, and int k = (k=2)+(k=4) yields 8, while int k = (k=2)+(k=4)+(k=5) gives 13. int k = (k=2)+(k=4)+(k=5)+(k=6) gives 19 (4+4+5+6).

My guess? The addition is done left to right. The first two (k=x) expressions are added, and the result is stored in a register or on the stack. However, since it is k+k for this expression, both values being added are whatever k currently is, which is the second expression because it is evaluated after the other (overriding its assignment to k). However, after this initial add, the result is stored elsewhere, so is now safe from tampering (changing k will not affect it). Moving from left to right, each successive addition reassigns k (not affected the running sum), and adds k to the running sum.

Upvotes: 0

Prasoon Saurav
Prasoon Saurav

Reputation: 92864

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

Upvotes: 7

Vagrant
Vagrant

Reputation: 1716

int i = i; first defines the variable and then assigns a value to it. In C you can read from an uninitialized variable. It's never a good idea, and some compilers will issue a warning message, but it's possible.

And in C, assignments are also expressions. The output will be "10", or it would be if you had a 'k' there, instead of an 'a'.

Upvotes: 0

Related Questions