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?

5
  • 2
    Dont use char*, use std::string instead.
    – Davidbrcz
    Dec 20, 2013 at 10:57
  • 2
    Either enable those compiler warnings (one of them should actually be an error in C++11) or pay attention to them.
    – chris
    Dec 20, 2013 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, 2013 at 10:58
  • @leewangzhong, If you don't know why that is, you might find this interesting: stackoverflow.com/questions/4685072/…
    – chris
    Dec 20, 2013 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, 2013 at 12:05

2 Answers 2

6

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

*x++;

is the same as

*(x++);

which really does the same as

x++;
1
  • 1
    Your first version was actually correct. Prefix-++ and * have the same precedence, postfix-++ has higher precedence.
    – arne
    Dec 20, 2013 at 10:55
5

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

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

1
  • I see. It's basically the same as str++; *str; and the latter statement doesn't do anything.
    – hello all
    Dec 20, 2013 at 13:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.