Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why typedef can not be used with static?

Tags:

Why typedef can not be used with static? For example, the code below is an error

typedef static int INT2; 

What other rules should be follow to use the typedef? What other keywords can not be used with typedef?

Thanks so much!

like image 928
skydoor Avatar asked Feb 07 '10 21:02

skydoor


People also ask

Is typedef a valid storage class in C?

Yes, typedef is a storage-class-specifier as you found in the standard.

When should you use typedef?

One good reason to use typedef is if the type of something may change. For example, let's say that for now, 16-bit ints are fine for indexing some dataset because for the foreseeable future, you'll have less than 65535 items, and that space constraints are significant or you need good cache performance.

What is the advantage to use the typedef to define a data type in a program?

Typedefs provide a level of abstraction away from the actual types being used, allowing you, the programmer, to focus more on the concept of just what a variable should mean. This makes it easier to write clean code, but it also makes it far easier to modify your code.

Why are typedef statements useful?

The typedef is an advance feature in C language which allows us to create an alias or new name for an existing type or user defined type.


2 Answers

typedef doesn't declare an instance of a variable, it declares a type (type alias actually),

static is a qualifier you apply to an instance, not a type, so you can use static when you use the type, but not when you define the type. Like this..

typedef int int32; static int32 foo; 
like image 131
John Knoeller Avatar answered Sep 23 '22 16:09

John Knoeller


The static keyword is not part of the type, depending on the context it is a storage or scope specifier and has no influence whatsoever on the type. Therefore, it cannot be used as part of the type definition, which is why it is invalid here.

A typedef is a type definition, i.e. you're saying 'this name' now refers to 'this type', the name you give must be an identifier as defined by the language standard, the type has to be a type specifier, i.e. an already named type, either base type or typedef'd, a struct, union, class, or enum specifier, with possible type qualifiers, i.e. const, or volatile.

The static keyword however does not change the type, it says something about the object, (in general, not in the OOP sense.) e.g. it is the variable that is placed in static storage, not the type.

It looks like you're trying to use a typedef as a macro, i.e.

#define MYINT static int 
like image 44
wich Avatar answered Sep 26 '22 16:09

wich