Ignoring why I would want to do this, just trying to understand what is happening here: This code compiles:
#include <stdio.h>
typedef char byte;
int main (void)
{
byte var_byte;
int byte = 10;
printf("\n Test program: %d\n", byte);
}
But, if I change the order in which the variables are declared, it does not compile.
This DOES NOT COMPILE:
#include <stdio.h>
typedef char byte;
int main (void)
{
int byte = 10;
byte var_byte;
printf("\n Test program: %d\n", byte);
}
Compiler error:
b.c:7:8: error: expected ‘;’ before ‘var_byte’
byte var_byte;
^~~~~~~~
Could someone please explain why order matters?
In this program
the name of the variable
byte
hides the name of the typedef.From the C Standard (6.2.1 Scopes of identifiers)
Pay attention to that the name of an identifier and a typedef name belong to the same name space.
The typedef name is declared in the global scope (file scope) while the name of the variable is declared in the inner block scope and the name of the variable hides the name declared in the global scope.
Consider this program.
Within the block scope of the function
main
(the inner scope relative to the file scope) the name of the typedef is hidden by the declaration of the variable with the same name.However inside the block scope of the function
f
the name declared in the typedef is visible because neither other declaration in the block scope of the function hides the name declared in the typedef.Here is a more interesting program that deals with the point of declaration (it is a C++ term)
Its output might look like
Here is in the file scope there is declared variable with the name
byte
In the outer block scope of the function
main
there is introduced typedef namebyte
.It hides the previously declared name
byte
after declaration of the declarator. That is in this typedefthe name
byte
in the square braces corresponds to the global namebyte
.Then in the inner block scope there is declared an array with the same name
byte
that hides the typedef name.Pay attention to that in the expression
there is used the name of the array not the typedef name.
Edit here: (misunderstand of the question)
When you declare a variable in C it does not look for
typedef
structures to see if a structure named the same with the variable. On the first code,this line of code comes before the declaration of the variable
int byte
. The computer will look for the most recent reference of the word byte as it was the structure name here.On the second one the the variable
int byte
does not return an error because you can still create variables with the same structure type name in C. But after you do so you can't create new structures to that structure as the computer will think that it is referring to the variable name and not the the structure type as the variable was declared most recently