C++ unexpected output
hey guys, doing some exercises after a section on scopes.
the question was Is the following program legal? if so, what values are printed? Code:
int i = 100, sum = 0; Code:
#include <iostream> Then i expected it to print 1 1 2 3 3 6 ... 10 55 but i got 100 55. Now as im typing this i am facepalming, because i think the i=0 is only defined in the for loop, and the std::cout line is calling the block? scope variable? is that right? man this stuff is tricky lol |
As you typed it, the 'for' loop ends with the semi-colon.
To see exactly what is going on, try this minor variation, using braces to define the for loop: Code:
#include <iostream> |
You did miss the 'i' in the first code block for the 'for' loop, but I assume that is a typo :)
Because your 'for' loop has not braces ({}) to scope the loop it is related that the 'for' loop has only a single line of code, which is the sum itself of 'sum'. Therefore, std:cout is outside the loop and the program will only return a single line with the 'main' value of 'i' which is 100 as 'i' used for the addition to 'sum' is internal (scoped) to the loop. |
thanks for clarifying, totally missed the braces part of it. Didn't realize i was doing a one line statement.
the printout from that code is more what i was expecting :) Thanks again! |
All times are GMT -5. The time now is 05:56 PM. |