Struct and typedef struct in C Language

Source: Internet
Author: User

Typedef is a key word in C language. It defines a new name for a data type. The data types here include internal data types (int, char, etc.) and Custom Data Types (struct, etc ).

In programming, typedef is generally used for two purposes. One is to give a variable a new name that is easy to remember and clear, and the other is to simplify some complicated type declarations.

As for the nuances of typedef, let's take a look at the specifics of several problems.

I

First, define a struct type in C to use typedef:

typedef struct Student{int a;}Stu;

So when declaring the variable, you can: Stu stu1;

If there is no typedef, it must be declared using struct Student stu1.

The Stu here is actually the alias of struct Student.

In addition, Student can also be left empty (so it cannot be struct Student stu1 ).

typedef struct{int a;}Stu;

However, in c ++

struct Student{int a;};

So Student is defined, and Student stu2 is directly used when variables are declared.

II

Second, if typedef is used in C ++, the difference may occur:

Struct Student {int a;} stu1; // stu1 is a variable typedef struct Student2 {int a;} stu2; // stu2 is a struct type

You can directly access stu1.a during use, but stu2 must first stu2 s2; and then s2.a = 10;

3.

You can master the above two items, but at last we will discuss some issues that do not matter much.

If we write:

typedef struct  {int num;int age;}aaa,bbb,ccc;

What is this?

I personally observe the understanding of the compiler (VC6), which is equivalent

typedef struct  {int num;int age;}aaa;typedef aaa bbb;typedef aaa ccc;

That is to say, aaa, bbb, and ccc are all struct types. When declaring a variable, you can use any one. This is also true in c ++. However, note that if the typedef keyword is written in c ++, aaa, bbb, and ccc will be completely different objects.

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.