Postfix increment issue in program! (Help.)

closed account (yR9wb7Xj)
I'm having a hard time understanding postfix increment in this while loop.

I know prefix increment such as ++x for example . . .
x= 4 y= ++x

here the x will increment 4 to become 5 and then it will evaluate the x therefore now y is x

but if was postfix increment

x =4 y= x++

x is being evaluated first and then it gets increment. So now x is 5 but y is 4 now? why is that?

Not sure if this right, but my question is how is the cValue postfix being seen here? For example it's evaluating if the cValue is <= to char Z, but then it increments it so it becomes A? I'm really confuse if someone can explain, thanks.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
/*
 *  Write a program that prints out the letters a through z along with their ASCII codes.
 *   Hint: to print characters as integers, you have to use a static_cast.
 */

#include <iostream>
using namespace std;
int main(){


	char cValue = 'a';

	while(cValue <= 'z'){

		cout << cValue  << " " << static_cast<int>(cValue) << "\n"<< endl;

		cValue++;

	}



	return 0;
}
Last edited on
It only matters within the same expression. (Often you can think of that as the stuff between semicolons.)

In your example above, it doesn't matter when on line 17 cValue is incremented -- it is the only thing happening.

You can read a little more about sequencing here:
http://www.cplusplus.com/faq/beginners/undefined/#sequencing

Hope this helps.
closed account (yR9wb7Xj)
Kind of, in the example of the reading link I'm guessing cValue is the sequence point because it's between the evaluation and the expression? Since it's postfix incrementing meaning cValue is being evaluated first then it gets incremented by 1.
If these were functions, they would look like:

1
2
3
4
5
6
7
8
9
10
11
12
13
int& prefix_increment( int& v ) // yields an lvalue
{
    v = v + 1 ; // increment v
    return v ; // and return it
}

int postfix_increment( int& v ) // yields a prvalue (pure rvalue)
{
    int copy_of_old_value = v ; // make a copy of v
    v = v + 1 ; // increment v
    return copy_of_old_value ; // return an anonymous temporary which holds 
                               // a copy of the old value (the value *before* increment)
}
closed account (yR9wb7Xj)
This was a great demonstration, thanks. I understand now, for the prefix increment function it's incrementing one and returns the new value, & postfix increment function it's duplicating the old value that's being evaluated and then it increments it by 1, returning the old value again that was duplicated.

Last edited on
Topic archived. No new replies allowed.