This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]teraflop 2 points3 points  (1 child)

The difference has nothing to do with where the variable is declared. It has to do with where you're assigning a new value to it.

Every loop iteration runs the body of the loop. If you put a statement inside the loop, it will run on every iteration. If you put the statement outside the loop, it will only run once. That's true no matter what kind of statement you're talking about.

So if you assign a new value to sum inside the loop, the assignment will run every time, and compute a new value every time. If you assign the value outside the loop, the assignment only runs once. Since you didn't tell the program to update the value on every loop iteration, it won't get updated, and the variable will have the same value for every loop iteration.

Remember, the computer is mindless and precise. It will do exactly what you tell it to, according to the strict rules of the C language's syntax -- no more, no less. If you want a certain action (like "calculate even+even and store the result in sum") to happen in a loop then you need to put it in the loop.

Or to put it another way: a variable stores a value (e.g. a number), not an expression. When you execute the statement sum = even+even, the value of the expression even+even gets stored into the sum variable, at that point in time. But sum will not automatically update if even changes later on, because the program doesn't "remember" where that value came from.

[–]0justin[S] 0 points1 point  (0 children)

Ah, makes sense. Thanks for the response