The interchange details of #define and typedef in C language _c language

Source: Internet
Author: User

Copy Code code 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%s%s%s%s\n ", A[0], a[1], a[2], a[3], b[0], b[1], b[2]);
return 0;
}


Replace the row of the TypeDef with #define, and the #define example that has been given cannot pass, but a single character can be added to the program.

==================== the answer to this question ===========================

What are the differences between the following two methods for defining PSTR data types? Which one is better?
typedef char* PSTR;
#define PSTR char*;

Answer and Analysis:

Generally speaking, a typedef is better than a #define, especially in a pointer situation. Take a look at the example:
typedef char* PSTR1;
#define PSTR2 char *
PSTR1 S1, S2;
PSTR2 S3, S4;

In the above variable definition, s1, S2, S3 are all defined as char *, and S4 is defined as char, not the pointer variable we expect, and the root cause is that #define is just a simple string replacement and the typedef is a new name for a type.
In the above example, the Define statement must be written as PStr2 S3, *s4; This can be done properly.

So the program

Copy Code code as follows:

#define String char *;
int main (void)
{
String a[] = {"I", "like", "to", "Fight,"},
*b[] = {"Pinch,", "and", "Bight."}; /*<--is here!! --*/
printf (%s%s%s%s%s\n ", A[0], a[1], a[2], a[3], b[0], b[1], b[2]);

return 0;
}


==========================
Very ingenious indeed!

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.