1

I have this:

...
int charry = 0;
if (l[charry++] == 'a'){
    whatever;
}
...

The question is: will charry be increased anyway or just if l[charry] == 'a' evaluates to true?

Thank you in advance.

Harshil Sharma
  • 2,016
  • 1
  • 29
  • 54
Zariweya
  • 295
  • 3
  • 13

2 Answers2

5

char is a reserved key word. Program would not even compile.


EDIT: Before comparison, both operand of == will be evaluated and hence any side effect to expressions will take place. Therefore charry will be modified.

haccks
  • 104,019
  • 25
  • 176
  • 264
  • My god..I just put that without thinking about it... Edited. – Zariweya Jul 13 '14 at 14:34
  • 1
    To be pedantic: The side effect will *not* necessarily have taken place before the comparison. At that point it's certain to happen, but it may be delayed until the next [sequence point](http://stackoverflow.com/q/4176328/395760) (which would be after the comparison). So if you did something more complicated like `if (l[charry++] == 'a' && charry == 1)` you'd have undefined behavior. –  Jul 13 '14 at 14:40
  • @delnan; I never said that side effect will take place "before/after". :) – haccks Jul 13 '14 at 14:43
  • 1
    So what? Still worth knowing :-) –  Jul 13 '14 at 14:44
3

It will absolutely be incremented by 1 after the if-statement. if you choose to name your variable something other than a reserved keyword.

int charry = 0;
if (l[charry++] == 'a'){
    whatever;
}
// charry is now 1

If charry is used again before the next sequence point, as user delnan explained in his comment, you would have undefined behaviour.

ThreeFx
  • 7,250
  • 1
  • 27
  • 51
  • Yeah, yeah, you guys are so critical (and I appreciate it). It was a mistake, I am not using "char" as a name, haha. – Zariweya Jul 13 '14 at 14:36
  • "It will be incremented ... after the if-statement" is a bit imprecise: It will be incremented sometime between reading the old value of `charry` and the branch decision of the `if()`. At least as far as the language is concerned. The optimizer, of course, may move the increment pretty much anywhere else as long as the code behaves as if the increment happened within the parentheses of the `if()`. – cmaster - reinstate monica Jul 13 '14 at 14:54