Your foo1() function returns a pointer to a local variable. Unfortunately, that local variable is not in scope upon return, so it is pointing to a location on the stack that will be reused with other function calls.
Jay Schwartzman wrote:Yes, but then why is it switching val and ptr to be the same in the if/else will not create that error
First of all, this should be compiler dependent -- so what you are seeing may not be with another compiler.
Anyway, if the two blocks are returning different results, I would speculate that it is the "else" block that is wrong. The reason is that the foo2() function reused the stack that was previously used by the foo1() function. Technically, the "if" block also has issues, but it has not yet been corrupted when the pointer is used in the later expression (since the foo2() function was used before the foo1() function).
That may be 1/2 right, when a do a line by line tracking, the else runs first since 0 is even and gives val0=108 then i is 1, and val 1 gives 10. Then these values never change. However if you switch in the else statement for val to be done first then ptr, both val 0, and val 1 stay 10 throughout the program. I don't understand why
Well, like I mentioned, this is a corruption (that is likely compiler dependent); so, if you want to understand how your compiler generated / optimized the code differently, so that the result is corrupted differently (or not corrupted at all), I think that you may be alone in your research.