Detailed description of # define and typedef interchange in C Language

Source: Internet
Author: User

Copy codeThe Code is as follows: # include <stdio. h>
/* <--------- # Define string char * ----> */
Typedef char * string;

Int main (void)
{
String a [] = {"I", "like", "to", "fight ,"},
B [] = {"pinch,", "and", "bight ."};
Printf ("% s \ n", a [0], a [1], a [2], a [3], B [0], B [1], B [2]);
Return 0;
}

Replace the row of typedef with # define, and the given # define example cannot pass. However, you only need to add a character to the program.

=============================== Answers to this question ======================== ==============

There are two methods to define the pStr data type. What are the differences between the two? Which one is better?
Typedef char * pStr;
# Define pStr char *;

Answer and analysis:

Generally, typedef is better than # define, especially when there is a pointer. See the example below:
Typedef char * pStr1;
# Define pStr2 char *
PStr1 s1, s2;
PStr2 s3, s4;

In the preceding variable definition, s1, s2, and s3 are both defined as char *, while s4 is defined as char, which is not the expected pointer variable, the root cause is that # define is a simple string replacement, while typedef is a new name for a type.
In the preceding example, the define statement must be written as pStr2 s3, * s4; so that the statement can be executed normally.

So the program

Copy codeThe Code is as follows: # define string char *;
Int main (void)
{
String a [] = {"I", "like", "to", "fight ,"},
* B [] = {"pinch,", "and", "bight."};/* <-- this is where !! --*/
Printf ("% s \ n", a [0], a [1], a [2], a [3], B [0], B [1], B [2]);

Return 0;
}

======================================
Really clever!

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.