First, first of all, do yourself a favor and properly format your code:
int main() {
int i, x = 1;
printf("%d\n", x);
for (i = 0; i < 4; i++) {
int x = 2;
printf("%d/ ", x);
{
int x = 3;
printf("%d/ ", x);
}
}
printf("\n%d", x);
}
Okay, so it’s easier to see what parts of the code are, how it’s organized and what’s inside of it. And the key to understanding what happens is this particular passage:
{
int x = 3;
printf("%d/ ", x);
}
Each time you open keys (with the character {
), is creating a new block, and as explained here, each block generates a new scope. That means that any variable created in there only exists in that block. Even if it has the same name as another variable created outside it, it doesn’t matter: although they have the same name, they are different variables.
See for example this code:
int main() {
int n = 0;
printf("Antes do bloco: %d\n", n);
{ // início do bloco
int n = 1;
printf("Dentro do bloco, novo n: %d\n", n);
n = 2;
printf("Dentro do bloco, mudando valor do n: %d\n", n);
} // fim do bloco
printf("Depois do bloco: %d\n", n);
n = 3;
printf("Depois do bloco, mudando valor do n: %d\n", n);
}
His way out is:
Antes do bloco: 0
Dentro do bloco, novo n: 1
Dentro do bloco, mudando valor do n: 2
Depois do bloco: 0
Depois do bloco, mudando valor do n: 3
That is, outside the block, what counts is the n
created in the first line of main
(in the case, the int n = 0
).
Inside the block I create a new n
(on the line int n = 1
), and as it was created inside the block, it only exists inside that block, and it’s not the same n
that was created outside of it (although they have the same name, they are different variables).
After the block ends, the n
"internal" (what "belongs" to the block) ceases to exist and returns to "worth" the n
"external" (what was created at the beginning of the main
).
In your case, you have more than one block: the for
creates a new scope, and within the for
has another block that creates another scope:
int main() {
int i, x = 1;
printf("%d\n", x); // esse é o x que foi criado na linha de cima
for (i = 0; i < 4; i++) {
int x = 2; // esse x vale para o escopo do for
printf("%d/ ", x);
{ // início do bloco
int x = 3; // esse x vale para o bloco iniciado na linha anterior
printf("%d/ ", x);
} // fim do bloco
}
printf("\n%d", x);
}
That is, beyond the x
created at the beginning of main
(the x = 1
), we still have what is created within the for
(the int x = 2
) and one more that is created in the block that is inside the for
(the int x = 3
). Although they have the same name, they are not the same variable, because each has its own scope.
"I thought it remained in the loop, different from the function that is forgotten" explain this better. There are some concepts involved here, for example if the variable is local, pointer, etc.
– Ricardo Pontual
this code also use two "x" variables, one global and one within the method
main
, pq do not use another name inside the main loop?– Ricardo Pontual