0
#include <iostream>
#include <cstring>

using namespace std;

int main() {
    char *str = "hello";

    while (*str) {
        cout << *str;
        *str++;
    }

    return 0;
}

and

#include <iostream>
#include <cstring>

using namespace std;

int main() {
    char *str = "hello";

    while (*str) {
        cout << *str;
        str++;
    }

    return 0;
}

both output

hello

Why doesn't adding or removing the deference operator before str++ alter the output?

hello all
  • 252
  • 2
  • 17
  • 2
    Dont use char*, use std::string instead. – Davidbrcz Dec 20 '13 at 10:57
  • 2
    Either enable those [compiler warnings](http://coliru.stacked-crooked.com/a/4bed875ce521867b) (one of them should actually be an error in C++11) or pay attention to them. – chris Dec 20 '13 at 10:57
  • 1
    Tip: When I need to remember operator precedence, I Google "c operator" and click the Wikipedia result. Also noteworthy: "a&b == 0" (with & being "bitwise and") means "a & (b==0)" – leewz Dec 20 '13 at 10:58
  • @leewangzhong, If you don't know why that is, you might find this interesting: http://stackoverflow.com/questions/4685072/c-operator-precedence-bitwise-lower-than – chris Dec 20 '13 at 11:55
  • Yep, I saw it before, and did find it interesting. I found out about it for PHP first and thought PHP was being silly. – leewz Dec 20 '13 at 12:05

2 Answers2

6

Postfix ++ has higher precedence than the de-rerference operator *, so

*x++;

is the same as

*(x++);

which really does the same as

x++;
juanchopanza
  • 223,364
  • 34
  • 402
  • 480
  • 1
    Your first version was actually correct. Prefix-`++` and `*` have the same precedence, postfix-`++` has higher precedence. – arne Dec 20 '13 at 10:55
5

*str++ means *(str++).

Since you don't use the value of that expression, the * has no effect.

Steve Jessop
  • 273,490
  • 39
  • 460
  • 699