Pointers

1
2
3
4
5
char a[] = "ABC";
    char *p = a;
    print(++*p);
    print(*p++);
    print(*p);


tbh i got tired from understanding this, they all will print
B
i dunno why tbh xD can someone explain why? i know some of them but i'd like someone more experienced to tell why all of them will print B.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
char a[] = "ABC";

char *p = a; // p points to the first character in the array.
             // "ABC"
             //  ^
             //  p

print(++*p); // Same as: ++(*p)
             // The character that p points to is incremented (i.e. The 
             // A is turned into a B).
             // "BBC"
             //  ^
             //  p

print(*p++); // Same as: *(p++)
             // The pointer p is incremented so that it points to the 
             // second character in the array. The expression (p++)
             // returns the old value of p (because post-increment was 
             // used) before it was incremented so the value that is 
             // printed is actually the first character in the array. It
             // doesn't matter though because the first and second 
             // character are equal.
             // "BBC"
             //   ^
             //   p

print(*p);   // Prints the character that p points to.
             // "BBC"
             //   ^
             //   p 
Thank you very much ! <3
Last edited on
@Peter87:

This code below, prints 4 3 2 2 2 and when I tried to use the same explanation you said up there i didnt get the same values :c what's new in this one?

1
2
3
             int b[] = {1,2,3,4,5,6};
             int *c = b;
             cout << *c <<" " << *c++<<" " << *c++ <<" "<< *c++ <<" "<< ++*c;



On the other hand, I got them when I used cout in this form:
1
2
3
4
5
6
7
8
9
10
11
int b[] = {1,2,3,4,5,6};
             int *c = b;
             cout << *c ;
             cout<<" " ;
             cout<< *c++;
             cout<<" " ;
             cout<< *c++;
             cout<<" ";
             cout << *c++;
             cout<<" ";
             cout<< ++*c;
Last edited on
hint: look-up pre-increment vs post-increment operators and operator precedence
On the other hand, I got them when I used cout in this form:


In the first "form" you had undefined behavior. Anything could've printed.

For an in-depth explanation, read the answers here:
http://stackoverflow.com/questions/4176328/undefined-behavior-and-sequence-points
Topic archived. No new replies allowed.