c++ - pointers and increment operator -


i have following simple code:

#include<iostream>  const char str[]={'c','+','+'};  int main() {    const char *cp=str;                        std::cout<<*str<<std::endl;    while (*cp++>0)       std::cout<<*cp; }  

can't understand why prints

c ++ 

shouldn't postfix increment operator evaluate expression return value unchanged? (i double checked precedence of increment, dereference , relational operators , should work)

your problem here:

while (*cp++>0)       std::cout<<*cp; 

the postfix operator increments value after the expression used in evaluated. there 2 different expressions referring cp in while statement though: first 1 tests , increments, second 1 prints. since second 1 separate statement, increment has happened then.

i.e. test against 'c', then increment regardless of result, print '+' through now-incremented pointer. if iterating string literal, code increment once after reaching 0, although don't see result of because skips print (because iterates on hand-created array no null terminator, here fall off end , exhibit undefined behaviour; big error in itself, can't rely on there being 0 @ end if 1 wasn't put there).


Comments

Popular posts from this blog

qt - Using float or double for own QML classes -

Create Outlook appointment via C# .Net -

ios - Swift Array Resetting Itself -