LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   C++ unexpected output (https://www.linuxquestions.org/questions/programming-9/c-unexpected-output-4175585595/)

iceman81 07-26-2016 09:48 PM

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;
for (int = 0; i != 0; ++i)
sum += i;
std::cout << i << " " << sum << std::endl;

so i fired up emacs and put it in...
Code:

#include <iostream>
int main()
{
  int i = 100, sum = 0;
  for (int i = 0; i <= 10; ++i)
    sum += i;
  std::cout << i <<  " " << sum << std::endl;
  return 0;
}

now i anticipated "int i = 0" to remove 100 and put 0.

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

notKlaatu 07-26-2016 10:06 PM

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>
int main()
{
  int i = 100, sum = 0;
  for (int i = 0; i <= 10; ++i) {
    std::cout << "for i=" << i << '\n';
    std::cout << "for sum=" << sum << '\n';
    sum += i;
  }
  std::cout << "Final int i=" << i <<  " " << sum << std::endl;
  return 0;
}

Oh, and yes the 'int i' in the for loop exists only in the for loop.

grail 07-26-2016 10:08 PM

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.

iceman81 07-26-2016 10:20 PM

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.