I’m using the book “Programming Principles and Practice using C++” to learn programming and one of the exercises is looping through the characters a-z using a while-loop.
Now, I have programmed with C++ and other languages before, so I decided to try to use as few lines as possible (while still using a while-loop). However, this came with the cost of my output being kind of messed up.
Code:
#include <iostream>
int main(){
char ch = 'a';
while(ch <= 'z')
std::cout << ch << '\t' << (int) ch++ << std::endl;
return 0;
}
Output:
b 97
c 98
d 99
e 100
...
x 119
y 120
z 121
{ 122
Now I do realize that this could’ve been done with a for-loop instead, and I did that as well (it worked). But I still don’t get what’s wrong with this code, and it’s really annoying me.
It appears as if I’ve told it to output “ch+1”, since it prints out ‘b’ where it should print ‘a’. The incrementing isn’t done until after the integer value of ch has been put into the out-stream (post-increment). And even if I had incremented it earlier, at least the printed characters and their integer values should correspond.
Any ideas of why this code isn’t working?
Short answer is that you have a bit of Undefined Behavior because you’re both modifying and using the value of the variable
ch, via separate sub-expressions, in the same expression.The Right Thing(TM) to do here is to use the most practical loop for the task at hand: