An article to understand C language typedef keywords

一、typedef VS #define

Before starting to explain the typedef keyword, I want to try to distinguish between typedef and define macro definitions . E.g:

/*#define 形式*/
#define COUNT int
/*typedef形式 */
typedef int COUNT;

Typedef has similarities with **#define**. The above two statements both use COUNT instead of int. But in fact, they are different. #define is processed during pre-compilation, it can only do simple string replacement, the second typedef is processed at compile time, in fact, it is not a simple string replacement, but a method like defining variables Name a type like that.

  • Case 1:
/*使用typedef方式*/
typedef int COUNT,*PCOUNT;
int main()
{
    
    
    COUNT a = 520;
    PCOUNT b,c;
    b = &a;
    c = b;
    printf("address of a = %p\n",&a);
    printf("address of a = %p\n",b);
    printf("address of a = %p\n",c);
}
  • Case 2:
/*使用#define方式*/
#include <stdio.h>
#include <stdlib.h>
#define COUNT int
#define PCOUNT int*
int main()
{
    
    
  COUNT a = 520;
  PCOUNT b,c;
  b = &a;
  c = b;
  printf("address of a = %p\n",&a);
  return 0;
}

Although case 2 can be compiled successfully, there will be a warning, to the effect that b is a pointer variable, and c is an int variable. Two different types of variables cannot theoretically be assigned!
#define counterexample

  • But why is there a warning?
  • Because #define is simply text replacement, so PCOUNT<=>int*, PCOUNT b,c<=>int b,c *; is it familiar? Isn’t this how we define a pointer variable and an int variable? !

Two, basic typedef

Don't talk nonsense, just explain the case!

typedef aliases variables

  • Case 3:
typedef int COUNT,*PCOUNT;
int main()
{
    
    
    COUNT a = 520;
    PCOUNT b,c;
    b = &a;
    c = b;
    printf("address of a = %p\n",&a);
    printf("address of a = %p\n",b);
    printf("address of a = %p\n",c);
}

typedef aliases the structure

  • Case 4:
#include <stdio.h>
#include <stdlib.h>
typedef struct Date
{
    
    
    int year;
    int month;
    int day;
}DATE,*PDATE;

int main()
{
    
    
  PDATE time; // PDATE time<=>DATE* time<=>struct Date* time
  time = (PDATE)malloc(sizeof(DATE));
  printf("请输入年份:");
  scanf("%d",&time->year);
  printf("请输入月:");
  scanf("%d",&time->month);
  printf("请输入日:");
  scanf("%d",&time->day);
  printf("%d-%d-%d",time->year,time->month,time->day);
  return 0;
}

Guess you like

Origin blog.csdn.net/dongjinkun/article/details/105412559