Zariweya
Zariweya

Reputation: 295

Operator ++ in an IF statement in C

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.

Upvotes: 1

Views: 93

Answers (2)

ThreeFx
ThreeFx

Reputation: 7360

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.

Upvotes: 3

haccks
haccks

Reputation: 106092

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.

Upvotes: 5

Related Questions