Why did I get this output?

So I was experimenting with the "for" loop stuff, seeing what all would give me error messages and stuff. Well here is the code I had:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>

int main()
{
	unsigned long int number;
	std::cout << "Enter the number to begin the countdown at" << std::endl;
	std::cin >> number;

	for (number; number >=1; --number)
	{
		std::cout << number << std::endl;
	}

	std::cout << "0" << std::endl;
	
	return 0;
}


It worked as expected, you input a number and then it counted down from there.

But I edited the code, expecting to get an error when compiling. I added a semicolon after the for stuff, so it looked like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>

int main()
{
	unsigned long int number;
	std::cout << "Enter the number to begin the countdown at" << std::endl;
	std::cin >> number;

	for (number; number >=1; --number);
	{
		std::cout << number << std::endl;
	}

	std::cout << "0" << std::endl;
	
	return 0;
}


The "for" line is what I changed. To my surprised it compiled, so then I tried it out, inputing the number "47". Instead of counting down, it gave me the output like this:

Enter the number to begin the countdown at
47 // I entered that
0
0

I can see where one zero came from, but how did it get the other zero. I know one came from the last cout statement, but I can't figure out where the other zero came from?
if, for, while, etc statements all run the instruction or code block which follows them.

If you have {braces} after a 'for' statement, those braces will be the loop body

If you DON'T have braces, then the loop body is up until the next semicolon.

For example, these two are equivilent:

1
2
3
4
5
6
7
8
9
for(number; number >=1; --number)   // braces, so everything in the braces is the loop body
{
    std::cout << number << std::endl;
}

//========

for(number; number >=1; --number)  // no braces, so only the code up to the next semicolon is the loop body
    std::cout << number << std::endl;



The problem with your code is you have a semicolon after the for loop. Therefore it thinks that the loop has an empty body

1
2
3
4
5
6
7
8
for (number; number >=1; --number)
    ;                  // the compiler sees this semicolon as the end of the loop body

  // this block has NOTHING to do with the loop.  It's run only after the above loop
  // completes
{
    std::cout << number << std::endl;
}


So what happens is your loop counts down 'number' to zero, while doing nothing each time.

Then after the loop is complete, you cout 'number' (which is zero... so that prints "0")

Then you print "0" again on the line below.

This is why you get two zeros.
Last edited on
Topic archived. No new replies allowed.