Difference between typedef and # define

Source: Internet
Author: User

Difference between typedef and # define


1. typedef

Typedef is the meaning of the type definition, but itInstead of defining a new type, you can create an alias for an existing type., Similar to the meaning of the reference,References are aliases of variables or objects, while typedef defines aliases of types.. Typedef has two main functions:


1.1 simplify complex type declarations

Simplify complex type declarations, or give existing types an alias with a clear meaning; for example:

Typedef bool (* FuncPointer) (int, double); // declares the pointer type FuncPointer of a function that returns the bool type and has two (int and double) parameters.

FuncPointer pFunc; // declares a FuncPointer type function pointer object pFunc


1.2 define platform-independent types

Define platform-independent types to avoid type differentiation between different platforms, such:

Use typedef to define platform-independent types.

For example, define a floating point type called REAL. On the target platform 1, make it the highest precision type:

Typedef long double REAL;

On Platform 2 that does not support long double, change:

Typedef double REAL;

On Platform 3 that is not supported by double, change:

Typedef float REAL;

That is to say, when using a cross-platform system, you only need to change the typedef itself, without any modifications to other source codes.

This technique is widely used in the standard library, such as size_t. In addition, because typedef defines a new type of Alias, rather than a simple string replacement, it is more robust than a macro.


1.3 combined use of struct

In C ++, the role of struct is the same as that of class, that is, the default access permission is different. struct is public by default, and class is private by default.

[Example 1.3.1 ]:

struct Person{string name;int age;float height;};Person person;

Defines a Struct type Person and a Person object person.


Or

struct Person{string name;int age;float height;}person;

Defines a Struct type Person, and declares the Person object at the same time.


However, in C language, the definition and declaration of struct should use typedef.

[Example 1.3.2 ]:

Typedef struct _ Person {string name; int age; float height;} Person; // This is an alias of the Person structure;

If there is no typedef, it must be declared using struct Person person;, for example:

[Example: 1.3.3]

struct Person{string name;int age;float height;};struct Person person;

Or

Struct Person {string name; int age; float height;} person; // person is the object of Person.


2. Differences between typedef and # define


2.1. Different execution times

The keyword typedef is valid in the compilation phase. Because it is in the compilation phase, typedef has the type check function.

# Define is a macro definition. It occurs in the preprocessing phase, that is, before compilation. It only performs simple and mechanical string replacement without any check.

[Example 2.1.1] typedef performs a type check:

typedef unsigned int UINT;void func(){UINT value = "abc";// error C2440: 'initializing' : cannot convert from 'const char [4]' to 'UINT'cout << value << endl;}

[Example 2.1.2] # define does not perform type check:

// # Define usage example: # define f (x) x * xint main () {int a = 6, B = 2, c; c = f () /f (B); printf ("% d \ n", c); return 0 ;}

The output result of the program is: 36. The root cause is that # define is a simple string replacement.

2.2. Different Functions

Typedef is used to define type aliases, platform-independent data types, and the use of struct.

# Define can not only take aliases for types, but also define constants, variables, and compilation switches.

2.3. different scopes

# Define has no scope restrictions. As long as it is a previously predefined macro, it can be used in future programs.

Typedef has its own scope.

[Example 2.3.1] there is no scope restriction, as long as it is pre-defined.

void func1(){#define HW "HelloWorld";}void func2(){string str = HW;cout << str << endl;}


[Example 2.3.2] And typedef has its own scope.

void func1(){typedef unsigned int UINT;}void func2(){UINT uValue = 5;//error C2065: 'UINT' : undeclared identifier}


[Example 2.3.3]

class A{typedef unsigned int UINT;UINT valueA;A() : valueA(0){}};class B{UINT valueB;//error C2146: syntax error : missing ';' before identifier 'valueB'//error C4430: missing type specifier - int assumed. Note: C++ does not support default-int};


In the above example, using UINT in Class B will cause an error because UINT is only in the scope of Class. In addition, the type alias defined with typedef in the class also has the corresponding access permission, [Example 2.3.4 ]:

class A{typedef unsigned int UINT;UINT valueA;A() : valueA(0){}};void func3(){A::UINT i = 1;// error C2248: 'A::UINT' : cannot access private typedef declared in class 'A'}


After adding the public access permission to the UINT, it can be compiled.

[Example 2.3.5 ]:

class A{public:typedef unsigned int UINT;UINT valueA;A() : valueA(0){}};void func3(){A::UINT i = 1;cout << i << endl;}


2.4. pointer operations

They have different functions when modifying the pointer type.

Typedef int * pint; # define PINT int * int i1 = 1, i2 = 2; const pint p1 = & i1; // p cannot be changed, and the content pointed to by p can be changed, equivalent to int * const p; const PINT p2 = & i2; // p can be changed. The content pointed to by p cannot be changed, which is equivalent to const int * p; or int const * p; pint s1, s2; // s1 and s2 are both int type pointers PINT s3, s4; // equivalent to int * s3, s4; only one is a pointer. Void TestPointer () {cout <"p1:" <p1 <"* p1:" <* p1 <endl; // p1 = & i2; // error C3892: 'p1': you cannot assign to a variable that is const * p1 = 5; cout <"p1:" <p1 <"* p1: "<* p1 <endl; cout <" p2: "<p2 <" * p2: "<* p2 <endl; // * p2 = 10; // error C3892: 'p2': you cannot assign to a variable that is constp2 = & i1; cout <"p2: "<p2 <" * p2: "<* p2 <endl ;}

Result:

P1: 00EFD094 * p1: 1

P1: 00EFD094 * p1: 5

P2: 00EFD098 * p2: 2

P2: 00EFD094 * p2: 5

References:

Summary on the usage of typedef

Differences between Typedef and define

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.