Increment Operator on Char

I have a question about using the increment operator (++) on a char variable. Here is the code in question:

#include <iostream>
using namespace std;

int main()
{
char n;
for (n = 1; n > 10, n++;)
{
cout << (n + 1) << endl;
}
return 0;
}

The point of this program was to show what happens when you mistakenly use a comma in place of a semicolon in a for loop. Now, I know that C++ will ignore the first conditional statement (n > 10) because I used a comma to connect it with the second "conditional" statement (n++). However, I do not understand why this program stops at n = 1 (after looping through from 3 to 128, -127 to 0, and finally back to 1). I know that if I declared n to be an int, then this program would give us an infinite loop. But, because I declared n to be a char, then I'm guessing that the increment operator (n++) points to pre-defined locations of memory for all the ASCII characters, and, for some reason, it stops again when n = 1. I am totally unclear on this process. If anybody could enlighten me, this would definitely help. Thanks!
The loop will stop when n++ evaluates as false. When will n++ evaluate as false? When n is zero. Because n++ is post-increment, the next thing to happen is increasing that zero to 1.

But, because I declared n to be a char, then I'm guessing that the increment operator (n++) points to pre-defined locations of memory for all the ASCII characters, and, for some reason, it stops again when n = 1

No, not at all. Absolutely wrong. Pre-defined locations holding all the ASCII chars? Doesn't exist. Under the hood, a char is just a single byte. How many values can a single byte hold (assuming an 8-bit byte, which is quite common)? 256. On your system, a signed char takes the values -127 to 128. So, n starts at 1, and goes up to 128, and when you add one to that it overflows and goes to -127, and then to -126, and so on all the way to zero, where the loop terminates, and the post-increment makes n one.
Last edited on
When I run your code it starts printing 3, 4, 5, ... but it doesn't wrap around when it reaches 128. Instead it just continues like if n was an int or something. Here you can see the output: http://ideone.com/456SA

Signed overflow is undefined so I guess that's why it behaves a bit strange.
Thank you both for responding.

Moschops: That definitely makes things clear to me. I guess I need to read up on post-incrementing.

Peter87: That is strange that your machine treats it like an int. I ran this using Eclipse Indigo on a Mac 10.5.7, and Moschops and I seem to be getting the same output.
Topic archived. No new replies allowed.