The interchange details of hashdefine and typedef in C language

  • 2020-04-01 23:31:54
  • OfStack


#include <stdio.h>

typedef   char *   string;       
int main(void)
{
   string   a[] = {"I", "like", "to", "fight,"},
   b[] = {"pinch,", "and", "bight."};
   printf("%s %s %s %s %s %s %sn", a[0], a[1], a[2], a[3], b[0], b[1], b[2]);
   return 0;
}

Replace the line of the typedef with #define, and the #define example that has been given won't pass, but you can just add a character to the program.

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

There are two ways to define a pStr data type. What is the difference? Which one is better?
Typedef char * pStr;
# define pStr char *;

Answer and analysis:

Generally, typedefs are better than #define, especially where there are Pointers. Here's an 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 *, while s4 is defined as char, which is not the pointer variable we expected. The fundamental reason is that #define is simply a string replacement and typedef is to give a new name to a type.
In the above example, the define statement must be written as pStr2 s3, *s4; That's how it works.

The program


#define    string    char *;        
int main(void)
{
   string   a[] = {"I", "like", "to", "fight,"},
   *b[] = {"pinch,", "and", "bight."};   
   printf("%s %s %s %s %s %s %sn", a[0], a[1], a[2], a[3], b[0], b[1], b[2]);
   return 0;
}

= = = = = = = = = = = = = = = = = = = = = = = = = =
Very clever indeed!


Related articles: