Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

typedef and non-simple type specifiers

Why is this code invalid?

typedef int INT;
unsigned INT a=6;

whereas the following code is valid

typedef int INT;
static INT a=1; 

?

As per my understanding unsigned int is not a "simple type specifier" and so the code is ill-formed. I am not sure though.

Can anyone point to the relevant section of the Standard which makes the first code invalid(and the second code valid)?

EDIT

Although Johannes Schaub's answer seemed to be correct and to the point(he had deleted his answer BTW) I accepted James Curran's answer for its correctness and preciseness.

like image 829
Prasoon Saurav Avatar asked Jul 20 '10 13:07

Prasoon Saurav


People also ask

What is typedef example?

typedef is used to define new data type names to make a program more readable to the programmer. For example: | main() | main() { | { int money; | typedef int Pounds; money = 2; | Pounds money = 2 } | } These examples are EXACTLY the same to the compiler.

How do you define a typedef?

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 the use of typedef in C++?

The typedef keyword allows the programmer to create new names for types such as int or, more commonly in C++, templated types--it literally stands for "type definition". Typedefs can be used both to provide more clarity to your code and to make it easier to make changes to the underlying data types that you use.

What is typedef declaration?

A typedef declaration is a declaration with typedef as the storage class. The declarator becomes a new type. You can use typedef declarations to construct shorter or more meaningful names for types already defined by C or for types that you have declared.


2 Answers

typedefs are not like macros. They are not just text substitution. A Typedef creates a new typename.

Now when you say unsigned int, the unsigned isn't a modifier which is tacked onto the int. unsigned int is the complete typename; it just happens to have a space in it.

So, when you say typedef int INT; then INT is the complete typename. It can't be modified.

static (like const) is a storage class specifier. It's not actually part of the type name.

like image 92
James Curran Avatar answered Sep 16 '22 17:09

James Curran


  • 7.1.1 : static is a storage class specifier. It can be placed before any type.
  • 7.1.5 : what is a type specifier (unsigned can be combined with char, long, short, or int)
like image 21
Scharron Avatar answered Sep 16 '22 17:09

Scharron