Block structure memory allocation for variables

for(int i=0;i<10;i++)
{
  int x=0;
  printf("%d",x);
   {
     int x=10;
     printf("%d",x);
   }
  printf("%d",x);
}

Here I want to know if memory will be allocated for variable x twice or is this value simply reset after exiting the second block, and memory is allocated only once (for x)?

+4
source share
4 answers

From the point of view of the C programming model, the two definitions xare two completely different objects. Assignment in the indoor unit will not affect the value xin the outdoor unit.

In addition, the definitions for each iteration of the loop are considered as different objects. Assigning a value to xin one iteration will not affect xin subsequent iterations.

, , , . , , , , , , i.

:

  • . x x. , , .

  • . 64- . , "" ( ) "" , .

, , .

for (int i = 0 ; i < 10 ; ++i)
{
    int x;
    if (i > 0)
    {
        printf("Before %d\n", x); // UNDEFINED BEHAVIOUR
    }
    x = i;
    printf("After %d\n", x);
}

( ), , , , , , , x , printf . undefined, , , .

+5

, , .

x ( ) . . ( ) x (x=0) - , x=10 - . , ().

C . :

A0 x==0 0x7ffc1c47a868
B0 x==0 0x7ffc1c47a868
C0 x==10 0x7ffc1c47a86c
D0 x==0 0x7ffc1c47a868
A1 x==0 0x7ffc1c47a868
B1 x==0 0x7ffc1c47a868
C1 x==10 0x7ffc1c47a86c
//Etc...

, C x 10, 0 D. , x . , , , . , ++, , ( ).

, , .

#include <stdio.h>

int main(void) {
    for(int i=0;i<10;i++)
    {
        int x=0;
        printf("A%d x==%d %p\n",i,x,&x);
        {
            printf("B%d x==%d %p\n",i,x,&x);
            int x=10;
            printf("C%d x==%d %p\n",i,x,&x);
        }
        printf("D%d x==%d %p\n",i,x,&x);
    }
}
+3

.

, , . .

- , , , .

, . . , CPU.

. , , .

+2

, , - . CPU x. , , , . , , , "" x, , - .

+1

Source: https://habr.com/ru/post/1684877/


All Articles