Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is typedef just a string replacement in code or somethings else?

Tags:

c++

c

syntax

I was curious to know how exactly typedef works.

typedef struct example identifier;

identifier x;

In above statement is 'identifier' just replaced (somethings like string replacement) with 'struct example' in code? If no, what does typedef do here?

please enlighten!

like image 660
KedarX Avatar asked Jul 16 '10 08:07

KedarX


People also ask

Is typedef just an alias?

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.

When should typedef be used?

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.

Does typedef create a new type?

Syntax. Note that a typedef declaration does not create types. It creates synonyms for existing types, or names for types that could be specified in other ways.

What is the difference between typedef and define?

typedef is limited to giving symbolic names to types only, whereas #define can be used to define an alias for values as well, e.g., you can define 1 as ONE, 3.14 as PI, etc. typedef interpretation is performed by the compiler where #define statements are performed by preprocessor.


1 Answers

No, it is not a string replacement - that would be macros. It creates an alias for the type.

typedefs are preferred over macros for custom types, in part because they can correctly encode pointer types.

typedef char *String_t;
#define String_d char *
String_t s1, s2;
String_d s3, s4;

s1, s2, and s3 are all declared as char *, but s4 is declared as a char, which is probably not the intention.

like image 174
Amarghosh Avatar answered Oct 20 '22 09:10

Amarghosh