Gibbs
Gibbs

Reputation: 22956

typedef cannot be used with type modifiers

typedef int WORD;
short WORD x =2;

Compiler throws an error. I have searched in the internet and books. I read that typedef cannot be used with type modidfers [unsigned, signed, long, short.]

And i found that it can be used in the following way.

 typedef short int WORD;
 WORD x =2;

Why typedef cannot be used with type modifiers?

Upvotes: 1

Views: 346

Answers (3)

alk
alk

Reputation: 70911

1st: short(as well as long and signed) are (also) "type specifiers" as for example int and float are.

The full list is (C11 Standard 6.7.2/1):

type-specifier:

  void
  char
  short
  int
  long
  float
  double
  signed
  unsigned
  _Bool
  _Complex

atomic-type-specifier

struct-or-union-specifier

enum-specifier

typedef-name

Certain of such are combineable (from the C11 Standard 6.7.2/2):

At least one type specifier shall be given in the declaration specifiers in each declaration, and in the specifier-qualifier list in each struct declaration and type name. Each list of type specifiers shall be one of the following multisets (delimited by commas, when there is more than one multiset per item); the type specifiers may occur in any order, possibly intermixed with the other declaration specifiers.

void

char

signed char

unsigned char

short, signed short, short int, or signed short int

unsigned short, or unsigned short int

int, signed, or signed int

unsigned, or unsigned int

long, signed long, long int, or signed long int

unsigned long, or unsigned long int

long long, signed long long, long long int, or signed long long int

unsigned long long, or unsigned long long int

float

double

long double

_Bool

float _Complex

double _Complex

long double _Complex

— atomic type specifier

— struct or union specifier

— enum specifier

— typedef name

To answer your question:

Why typedef cannot be used with type modifiers?

As you can see from the list(s) above the C langauge does not define combining a typedef name with any other type specifier to be valid.

Upvotes: 2

Dr. Debasish Jana
Dr. Debasish Jana

Reputation: 7118

typedef is for defining type, you cannot use any qualifier.

typedef int WORD;
short WORD x =2; // incorrect
WORD x =2; // correct

What you want is more of a preprocessor macro like:

#define WORD int
short WORD x = 2; // valid

Upvotes: 4

Lundin
Lundin

Reputation: 213711

In Deep C, i read that typedef cannot be used with type modidfers [unsigned, signed, long, short.] Why typedef cannot be used with type modifiers?

That's nonsense.

Compiler throws an error.

Because typedef is not text replacement. You can only use one type per declaration. So short WORD x makes as little sense as double int x.

Upvotes: 4

Related Questions