Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

For-loop Local Variables in C

Tags:

c

Why does the following code output the same memory location everytime?

int x;
for (x = 0; x < 10; x++) {
    int y = 10;
    printf("%p\n", &y);
}

I thought that the memory location should change as each time the for-loop is run, the variable is new.

like image 505
Amandeep Grewal Avatar asked Feb 27 '11 22:02

Amandeep Grewal


People also ask

Are for loops local variables?

In Python, on the other hand, variables declared in if-statements, for-loop blocks, and while-loop blocks are not local variables, and stay in scope outside of the block.

Are variables in for loop local or global?

For the most part, loops do not have their own scope, so the variable's scope will be the scope of wherever the for loop lives. With that in mind, if the for loop is within a function, it will have local scope. One exception would be using let x = something in Javascript.

What is local variable in C with example?

Local Variable: A local variable is a type of variable that we declare inside a block or a function, unlike the global variable. Thus, we also have to declare a local variable in c at the beginning of a given block. A user also has to initialize this local variable in a code before we use it in the program.

Can you return local variables in C?

Yes you are returning an array, which is actually a pointer behind the scenes, to the address of the memory location where the contents of the variable you've initialised is stored.


2 Answers

Yes, the variable is new each time around, but at the end of the block any new variables on the stack are released again.

Hence next time around the stack pointer is back exactly where it was. NB: this behaviour is common, but not guaranteed by the standards.

like image 45
Alnitak Avatar answered Sep 21 '22 06:09

Alnitak


Yes, you are absolutely right that the memory location could change. But it doesn't have to :). In each iteration the old variable is "destroyed" and a new one is "created" at the same place. Although any decent compiler would optimize the unnecessary "actions" away

like image 189
Armen Tsirunyan Avatar answered Sep 20 '22 06:09

Armen Tsirunyan