Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

typedef did not replaced with the datatype

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.

like image 772
Gokul Kulkarni Avatar asked Oct 11 '13 05:10

Gokul Kulkarni


People also ask

Does typedef create a new data type?

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.

What is typedef struct in C++?

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.

What is the scope of a typedef?

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.


1 Answers

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
}
like image 117
Yu Hao Avatar answered Oct 12 '22 23:10

Yu Hao