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 what. And the key to understanding what happens is this specific stretch:{
int x = 3;
printf("%d/ ", x);
}
Each time you open keys (with the character {), is creating a new block, and https://pt.stackoverflow.com/q/323998/112052 , each block generates a new https://pt.stackoverflow.com/q/135572/112052 . That means that any variable created in there exists only 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 exit 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, out of the block, what is worth is n created in the first line of main (in the case, int n = 0).Inside the block I create a new n (in line int n = 1), and as it was created within the block, it only exists within that block, and it is not the same n that was created outside of it (though they have the same name, they are different variables).After the block ends, the n "internal" (which "belongs" to the block) ceases to exist and goes back to "valer" n "external" (which was created at the beginning of main).In your case, you have more than one block: for creates a new scope, and within 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 x created at the beginning of main (o) x = 1), we still have what is created within for (o) int x = 2) and one more that is created in the block which is inside for (o) int x = 3). Although they have the same name, they are not the same variable, because each has its own scope.