-6
i=2;

i= ++i + ++i + ++i;

printf(i)

Please give the output with explanation?
The answer I'm getting is 12 but it should be 13.

Anri
  • 6,175
  • 3
  • 37
  • 61
  • I strongly advise you to look for already existing questions before writing your own one. Use Google for search. – Gangnus Mar 12 '13 at 11:40
  • There should be a script to detect this repetitive gunge and auto-reply, (and on C++ too). It might be nice if, just occasionally, the var name changed from 'i'. It's never 'j', or 'index', or 'banana' - it's always 'i'. – Martin James Mar 12 '13 at 12:46
  • Unfortunalely we *do* have questions about `j++`, as well as about a, b, c, p, k, s, u, v, x, y, and z. And both `++` and `--`, and both pre and post operators. [Look here](http://stackoverflow.com/search?page=2&tab=relevance&q=url%3a%22http%3a%2f%2fstackoverflow.com%2fquestions%2f949433%2f*%22) – Bo Persson Mar 12 '13 at 18:10

2 Answers2

5

The behavior of your code is undefined according to the C standard, as you are not allowed to use the preincrement operator more than once within the same expression. The output can be anything whatsoever.

See the answer to this question for a more comprehensive treatment of the topic.

Community
  • 1
  • 1
user4815162342
  • 141,790
  • 18
  • 296
  • 355
-4

Though the behaviour is undefined, IN UR CASE IT HAS BEEN EXECUTED AS, CONSIDERING THE PARSING IS FROM left, i = 5 + 4 + 3 = 12

For explanation, i = (++i) + (++i) + (++i) Now i = 2, so first ++i expands as 3 and i becomes i=3 i = (++i) + (++i) + 3

Now i = 3, so ++i expands as 4 and i becomes i=4 i = (++i) + 4 + 3

Now i = 4, so first ++i expands as 4 and i becomes i=5 i = 5 + 4 + 3

hazzelnuttie
  • 1,403
  • 1
  • 12
  • 22