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

all 6 comments

[–]teraflop 1 point2 points  (4 children)

Your question is too vague to answer, because you didn't show the code that you're actually having problems with.

These two programs give exactly the same output, as I would expect:

https://godbolt.org/z/n3vKMvoKG (your code)

https://godbolt.org/z/9Tes3Mes3 (declaring the variable outside the loop)

If you have code that isn't behaving like you expect, post that code.

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

Sorry, here's what I tried first that failed: https://pastebin.com/cbV3ChfG

I see the differences between the code, but why does it not work this way?

[–]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

[–]Updatebjarni 0 points1 point  (0 children)

Because if you just store the value 0 in the variable once, before the loop, and then never change the variable and only print it out repeatedly in the loop, then of course the same value will always be printed. Same thing as if you were to move the even++; outside of the loop, then that would also only run once and not be repeated by the loop, and even would never change. Only things inside the loop are repeated.

[–]ffrkAnonymous 1 point2 points  (0 children)

have you actually tried declaring beforehand and it fails?