1

i am using g++ (GCC) 4.6.0 and i am having trouble to producing the correct result. given the following simple for loop in c++

  void sum(){
  int sum;
  for(int i=0,sum=0;i<=10;sum+=i,++i);
  cout << sum << endl;
  }

the output is giving me 0. suppose within the for loop i added

  cout << sum << endl;

it give me 0,1,3... until the very last line 0;

I think the reason I am getting 0 is because variable shadowing in the for loop? so I tried ::sum as in ::sum=0, and ::sum +=i. but it complains by the compiler. Also I tried

  for(sum=0,int i=0;i<=10;sum+=i,++i); 

the compiler also complains about not having primary expression in the first clause in the for loop

3
  • Please include the results you actually expect this to produce. Commented Aug 8, 2011 at 22:29
  • 1
    @Martin: Why answer in a comment? Answer in an answer... except that several people already did. Commented Aug 8, 2011 at 22:46
  • A while loop would be even sweeter here: ideone.com/gdm6O :p Commented Aug 9, 2011 at 10:45

6 Answers 6

8

Really, you have to use the identifier sum three times for three different things? :-S

Just write it readbly:

int sum = 0;
for(int i = 0; i <= 10; ++i) { sum += i; }

No more confusion, no more shadowing, no more uninitialized variables. Who are you trying to trick? Think about your replacement who will have to learn and understand your code!

Tip: Turn on compiler warnings!

PS: Before anyone talks about efficiency and starts counting CPU cycles: a) don't. b) hug your wife. c) compare the assembly of this code and your code.

Sign up to request clarification or add additional context in comments.

Comments

6

int i=0,sum=0 is not the same as int i=0; sum=0;. It is one statement that declares two variables.

This means that you are shadowing the outer sum:

void sum() {
  int sum; // <-- one `sum`
  for (int i=0,sum=0;i<=10;sum+=i,++i) {} // <-- second `sum`
  cout << sum << endl;
}

Only a declaration statement like that can be in the first clause of the for preamble (think about whether sum=0,int i=0 would be valid elsewhere in your code), but you can workaround this issue by pulling out the "initialisation" to 0 entirely:

void sum() {
   int sum = 0;
   for (int i = 0; i <= 10; sum += i, ++i) {}
   cout << sum << endl;
}

Or, so that it's actually legible:

void sum() {
   int sum = 0;
   for (int i = 0; i <= 10; i++) {
      sum += i;
   }
   cout << sum << endl;
}

9 Comments

@dalle: If you click on the links, you'll see that I did not.
@dalle: On the comma operator, [2003: 5.18/1] says: "[..] All side effects (1.9) of the left expression [..] are performed before the evaluation of the right expression." (emphasis mine)
But now you have edited the answer. you had sum += ++i at first, which is not the same as sum += i, ++i.
@dalle: OK. That must have been one of the very first revisions, whilst I was looking up that clause; it wasn't there for long!
Yes, true, probably one of the first revisions. Anyway, +1 now when you have changed it.
|
4

Change your code to:

 void sum(){
  int sum = 0;
  for(int i=0;i<=10;sum+=i,++i); // all work is in for loop
  cout << sum << endl;
 }

Some (older) compilers wouldn't allow your original code, because you were defining a second sum inside your for loop which was hiding the original one. So, it was accumulating correctly within the for loop, but the sum defined outside the for loop was left untouched. For a little more detail:

int i = 0, sum = 0;

is the same as:

int i = 0;
int sum = 0;

8 Comments

I know I can do sum=0 outside of the for loop. but I want to take advantage of the inital phase of the for loop.
@cplusnewbieeeee: Why? It is no more efficient to do so, limits the visibility of sum to inside of the for loop, and makes the code less readable (as Kerrek SB rightly points out). Fewer lines of code != better code.
Note that the gcc behaviour is actually compliant with the standard.
@pmr: yeah, I'm thinking of older compilers I've used that technically weren't compliant. In this case, that bug would be a "feature".
@Ben I never doubted that you know it. IMHO The wording you used in the answer just makes it sound like it's the other way around.
|
3

You have two different sum variables. One declared in the

int sum;

line, and another one declared in the initializing declaration of your for loop.

The first part of a for statement is either a single declaration or an expression. In the latter case, the expression can consist of several assignments separated by comma operators, but you cannot mix and match declarations and expressions in one for loop. Thus, int i=0, sum=0 will be parsed as one declaration that declares i and sum. So in your loop you increase the inner sum, but after the loop only the outer one is visible, and that has still has whichever garbage value it started out with.

(Also, shame on you for putting the meat of the loop in the update expression instead of in the body!)

Comments

0

You are right. Solution is to do this this way:

void sum(){
    int sum = 0;
    for(int i=0;i<=10;sum+=i,++i);
    cout << sum << endl;
}

Comments

-1

Why did you put the ; after for-loop? Because of this you have 10 iterations of loop without any output and finally you have your result - zero.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.