I was surprised with the following piece of code,
#include<stdio.h>
typedef int type;
int main( )
{
type type = 10;
printf( "%d", type );
}
This went through and output of the program is 10.
But when I changed the code slightly as below,
#include<stdio.h>
typedef int type;
int main()
{
type type = 10;
float f = 10.9898;
int x;
x = (type) f;
printf( "%d, %d", type, x);
}
in aCC compiler:
"'type' is used as a type, but has not been defined as a type."
in g++ compiler:
"error: expected `;' before f"
Is it that the compiler did not recognize the pattern in the second case, as this pattern can be related to assignment of a variable, evaluation of an expression etc and in the first case as this pattern is only used while defining a variable compiler recognized it.
typedef is a reserved keyword in the programming languages C and C++. It is used to create an additional name (alias) for another data type, but does not create a new type, except in the obscure case of a qualified typedef of an array type where the typedef qualifiers are transferred to the array element type.
In C++, a typedef name must be different from any class type name declared within the same scope. If the typedef name is the same as a class type name, it can only be so if that typedef is a synonym of the class name. This condition is not the same as in C.
A typedef is scoped exactly as the object declaration would have been, so it can be file scoped or local to a block or (in C++) to a namespace or class.
typedef
identifiers, like variable names, also has a scope. After
type type = 10;
the variable type
shadows the type name type
. For instance, this code
typedef int type;
int main( )
{
type type = 10;
type n; //compile error, type is not a type name
}
won't compile for the same reason, in C++, you can use ::type
to refer to the type name:
typedef int type;
int main( )
{
type type = 10;
::type n; //compile fine
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With