I had a doubt that there is something i am missing seeking for the difference between Declaration and Definition and i found the link https://www.geeksforgeeks.org/commonly-asked-c-programming-interview-questions-set-1/ Its stated here that
// This is only declaration. y is not allocated memory by this statement
extern int y;
// This is both declaration and definition, memory to x is allocated by this statement.
int x;
Now if I go by the below piece of code
int main()
{
{
int x = 10;
int y = 20;
{
// The outer block contains declaration of x and y, so
// following statement is valid and prints 10 and 20
printf("x = %d, y = %d\n", x, y);
{
// y is declared again, so outer block y is not accessible
// in this block
int y = 40;
x++; // Changes the outer block variable x to 11
y++; // Changes this block's variable y to 41
printf("x = %d, y = %d\n", x, y);
}
// This statement accesses only outer block's variables
printf("x = %d, y = %d\n", x, y);
}
}
return 0;
}
I will get the below result
x = 10, y = 20
x = 11, y = 41
x = 11, y = 20
If i modify just the int y = 40 in the innermost block to y = 40 then the code will look like
//int y;
int main()
{
{
int x = 10;
int y = 20;
{
// The outer block contains declaration of x and y, so
// following statement is valid and prints 10 and 20
printf("x = %d, y = %d\n", x, y);
{
// y is declared again, so outer block y is not accessible
// in this block
y = 40;
x++; // Changes the outer block variable x to 11
y++; // Changes this block's variable y to 41
printf("x = %d, y = %d\n", x, y);
}
// This statement accesses only outer block's variables
printf("x = %d, y = %d\n", x, y);
}
}
return 0;
}
and the result will be
x = 10, y = 20
x = 11, y = 41
x = 11, y = 41
My friend told me this is because we are declaring a new y which is local to the block in the first code and that is not in the second case , i didn't get why as we are only writing the data type in front of the variable a second time , does this mean by writing data type we reserved a new memory space and created a new variable , please explain .
If i go by another article on Stackoverflow on the Link What is the difference between a definition and a declaration?
i see that whenever we say that we are Declaring a Variable, the variable is preceded by the extern keyword and i am speaking strictly related to C and not any other language.
So can we generalize to Declaration of variable as preceded by extern Keyword.
I understand my English might be bad and difficult for you to understand , please bear with me.