What are C typedef Struct Explained- Free Embedded C Programming Course

🚀 Learn BLE on Linux (BlueZ) – Programming Part 1

Hands-on Bluetooth Low Energy course. Special price: ₹399

Enroll Now on Udemy →
💬 Need help or career guidance? Ask us!Contact Us →

Free C Programming Course · Structure and Union

C typedef Struct Explained

Name your structures cleanly, build self-referential nodes the right way, and see the compiler errors for yourself. Part of the free embedded C course.

Every structure you declare in C makes you type the word struct again and again. The typedef struct in C pattern removes that repetition by giving the structure a short, meaningful name such as pkt_node_t or task_t. It looks trivial until you write a linked list node, and then the alias you just created refuses to work inside its own definition. This lecture of our free C programming course explains why that happens, shows two clean fixes, and runs real code so you can see the compiler behaviour yourself.

typedef struct in Cfree C programming courseembedded C programmingfree embedded C courselinked list nodestruct tag

What You Will Learn

  • How typedef struct in C creates a second name for a structure type
  • The three ways to declare a structure and when each one fits
  • Why a typedef alias cannot be used inside its own struct body
  • Two correct ways to write a self-referential node
  • How to compile and run the examples and read the output
  • Naming and style rules used in real embedded C programming projects

Prerequisites

You should already be comfortable with defining structures, the dot operator, pointers to structures and the arrow operator from the earlier lectures of this chapter. A working GCC installation is enough for every example here. The free embedded C course assumes no board; everything runs on a normal Linux or Windows machine.

Why Typedef Struct in C Exists

A structure type in C has a two-part name. The word struct is part of the name, followed by the tag. So a variable of the type needs the full phrase every time: struct sensor_sample s;, void print(struct sensor_sample *p), and so on. In a firmware project with hundreds of such declarations that is noise. A typedef lets you register a one-word name and use that instead.

There are three benefits, and they matter in different ways. Readability comes first: pkt_node_t says what the object is, while the word struct only says how it was declared. Second, you stop repeating the keyword. Third, a typedef is the single place to change when a type moves between targets, which we cover in the next lecture.

Three Ways to Declare a Structure

StyleDeclarationUse the type asCan point to itself?
Tag onlystruct pkt { ... };struct pkt x;Yes, through struct pkt *
Anonymous + typedeftypedef struct { ... } pkt_t;pkt_t x;No, the alias is not visible inside
Tag + typedeftypedef struct pkt { ... } pkt_t;pkt_t x; or struct pkt x;Yes, through struct pkt *

The anonymous form is the shortest and is perfect for plain data records such as a register snapshot or a configuration block. The moment a structure needs a pointer to another object of its own type, you need the tag.

How the Compiler Reads a Typedef Struct

The compiler reads declarations strictly from left to right. When it meets typedef struct pkt_node { ... } pkt_node_t; it does three things in order, and the order explains every surprise in this lecture.

Order in which the compiler registers names
Step 1
tag pkt_node becomes known
Step 2
body is parsed, tag is usable
Step 3
closing brace reached
Step 4
alias pkt_node_t registered after semicolon

The tag is registered the moment the compiler sees struct pkt_node {, so inside the braces you can write struct pkt_node *next;. The alias, on the other hand, is created by the declarator that follows the closing brace. Until the semicolon is processed, the compiler has never heard of pkt_node_t.

Typedef Struct in C with Self-Referential Nodes

A self-referential structure holds a pointer to another object of the same type. Linked lists, queues of packets and lists of RTOS tasks all work this way. Here is the mistake almost every beginner makes, followed by the exact compiler message.

#include <stdio.h>

/* BROKEN: the typedef name 'node_t' does not exist yet inside the braces */
typedef struct {
    int data;
    node_t *link;
} node_t;

int main(void)
{
    node_t n = { 1, NULL };
    printf("%d\n", n.data);
    return 0;
}

Compile it and GCC stops at the line that uses the alias:

$ gcc -std=c11 -Wall -Wextra typedef_bad1.c
typedef_bad1.c:6:5: error: unknown type name 'node_t'

Common Mistake

Using the alias inside its own braces. Because the structure has no tag in the broken example, there is no name at all that the pointer member can use. Either give the structure a tag, or declare the alias before the structure is defined.

Fix 1: Add a Tag

Give the structure a tag and use the tag for the self pointer. Keep the alias for everything outside the braces.

Fix 2: Forward Typedef

Write typedef struct task task_t; first. This declares the alias for an incomplete type. You can then write task_t *next; inside the later definition because the alias already exists. This style is popular in header files because other headers can use the alias without seeing the full body.

The program below uses both styles. The type names and values are our own embedded-flavoured example: a chain of packets and a short list of task priorities.

#include <stdio.h>
#include <stdlib.h>

/* Style 1: tag + typedef name that differ. Tag is usable inside the struct. */
typedef struct pkt_node {
    unsigned id;
    struct pkt_node *next;      /* must use the tag here */
} pkt_node_t;

/* Style 2: forward typedef first, then define. Name works inside. */
typedef struct task task_t;
struct task {
    int prio;
    task_t *next;               /* typedef name already visible */
};

int main(void)
{
    pkt_node_t c = { 3, NULL };
    pkt_node_t b = { 2, &c };
    pkt_node_t a = { 1, &b };

    for (pkt_node_t *p = &a; p != NULL; p = p->next)
        printf("pkt %u\n", p->id);

    task_t t2 = { 9, NULL };
    task_t t1 = { 5, &t2 };
    for (task_t *p = &t1; p; p = p->next)
        printf("task prio %d\n", p->prio);
    return 0;
}

Build and Run

$ gcc -std=c11 -Wall -Wextra -o typedef_self typedef_self.c
$ ./typedef_self
pkt 1
pkt 2
pkt 3
task prio 5
task prio 9

Both lists are walked with the same idiom: start at the head, print, move to next, stop at NULL. The only thing that differs between the two structures is how the type was named.

Three pkt_node_t objects linked by their next pointer
a
id 1, next holds address of b
b
id 2, next holds address of c
c
id 3, next holds NULL

Reading the Declarations Correctly

Two details trip people up when they read typedef code. First, the alias sits where a variable name would normally sit. If you delete the word typedef from typedef struct pkt_node { ... } pkt_node_t;, you get a declaration of a variable called pkt_node_t. The typedef keyword flips that identifier from a variable name into a type name. Second, the typedef declaration can list several aliases in one go, including pointer aliases, for example typedef struct pkt_node pkt_node_t, *pkt_node_ptr;. Use that sparingly. Hiding a pointer behind an alias makes code harder to read, because the star disappears from every declaration.

Real-World Uses in Embedded C Programming

Where you meet itTypical typedef struct in CWhy a tag is needed
RTOS task listtask_t with next linkScheduler walks a chain of tasks
Radio or UART packet queuepkt_node_t holding a buffer and lengthPackets wait in a linked queue
Device configurationadc_cfg_t recordNo self pointer, anonymous form is enough
Opaque driver handletypedef struct dev dev_t; in a headerBody stays private in the .c file

The last row deserves attention. When a library header says only typedef struct dev dev_t;, callers can pass dev_t * around but cannot touch the members, because the body is defined privately. That is one of the cleanest uses of a forward typedef in firmware.

Common Mistakes with Typedef Struct in C

MistakeSymptomFix
Alias used inside its own bodyunknown type nameUse the struct tag or a forward typedef
Forgetting the semicolon after the aliasStrange errors on the next lineAlways end the declaration with a semicolon
Using typedef and expecting a new, safer typeMixing types compiles silentlyAn alias is the same type; wrap values in a struct if you need type safety
Hiding pointers in aliasesUnclear ownership and const behaviourKeep the * visible in declarations

Best Practices

  • Give a tag to every structure that might ever need a self pointer, even if it does not today.
  • Pick one naming style per project and keep it. Many teams use a lower-case name with a _t suffix. POSIX reserves names ending in _t in its own headers, so larger libraries often add a project prefix.
  • Put forward typedefs in headers and struct bodies in the source file when callers should not see the members.
  • Prefer small, descriptive names over short cryptic ones.
  • Follow the style of the project you join. The Linux kernel coding style, for instance, avoids typedefs for ordinary structures, while many bare-metal code bases use them everywhere.

Performance and security notes. A typedef has no cost at run time, because it is resolved completely during compilation. From a security angle, an opaque typedef reduces accidental misuse of internal fields, but it does not protect memory; the usual pointer rules still apply.

Summary and Key Takeaways

  • typedef struct in C adds a name; it never creates a new type.
  • The struct tag exists inside the braces; the alias does not.
  • Self-referential structures need the tag or a forward typedef.
  • Tag and typedef name may be identical because they live in separate name spaces.
  • Typedefs cost nothing at run time and improve readability.

Conclusion

Once you remember the order in which the compiler registers names, typedef struct in C stops being mysterious. The tag arrives first and works inside the braces; the alias arrives last and works everywhere afterwards. Write a tag whenever a node must point to its own kind, use a forward typedef when you want clean headers, and keep the pointer star visible. In the next lecture of this free embedded C course we move on to what a typedef is really good for in firmware: keeping code portable across targets whose basic types differ in size.

typedef struct in C FAQ

What does typedef struct in C actually do?

It gives an existing structure type an additional name. The compiler still treats the new name and the original struct tag as the same type, so there is no runtime cost and no change in layout or sizeof.

Do I need a tag name when I use typedef struct in C?

Only when the structure must refer to itself, such as a linked list node or a tree node. Inside the braces the typedef alias does not exist yet, so the self pointer has to use struct tag *. If the structure never mentions itself, an anonymous struct with a typedef name works fine.

Why do I get ‘unknown type name’ inside my own struct?

The alias is registered only after the closing semicolon of the typedef declaration. Any use of the alias between the braces refers to a name the compiler has not seen. Use the struct tag, or add a forward typedef line before the struct body.

Can the tag and the typedef name be identical?

Yes. Tags and ordinary identifiers live in different name spaces in C, so typedef struct node { ... } node; is legal. The same name then works both as struct node and as node. This is a C feature; C++ rules differ slightly.

Does the Linux kernel use typedef struct?

The kernel coding style discourages new typedefs for plain structures, mainly because they hide the fact that a type is a struct. Bare-metal firmware and many RTOS code bases use them heavily for readability. Follow the style of the code base you are working in.

Is typedef struct in C the same as a #define macro?

No. A typedef is processed by the compiler and obeys scope and type rules. A macro is plain text substitution done by the preprocessor, which is why macros fail for pointer types and for declaring several variables in one line.

Does typedef affect memory usage or speed?

No. A typedef only creates a name. The generated machine code is identical with or without it.

Keep Going with the Free Embedded C Course

Next we use typedef for portability across targets, then work through the structure exercises with real compiler output.

{ “@context”: “https://schema.org”, “@type”: “FAQPage”, “mainEntity”: [ { “@type”: “Question”, “name”: “What does typedef struct in C actually do?”, “acceptedAnswer”: { “@type”: “Answer”, “text”: “It gives an existing structure type an additional name. The compiler still treats the new name and the original struct tag as the same type, so there is no runtime cost and no change in layout or sizeof.” } }, { “@type”: “Question”, “name”: “Do I need a tag name when I use typedef struct in C?”, “acceptedAnswer”: { “@type”: “Answer”, “text”: “Only when the structure must refer to itself, such as a linked list node or a tree node. Inside the braces the typedef alias does not exist yet, so the self pointer has to use struct tag *. If the structure never mentions itself, an anonymous struct with a typedef name works fine.” } }, { “@type”: “Question”, “name”: “Why do I get ‘unknown type name’ inside my own struct?”, “acceptedAnswer”: { “@type”: “Answer”, “text”: “The alias is registered only after the closing semicolon of the typedef declaration. Any use of the alias between the braces refers to a name the compiler has not seen. Use the struct tag, or add a forward typedef line before the struct body.” } }, { “@type”: “Question”, “name”: “Can the tag and the typedef name be identical?”, “acceptedAnswer”: { “@type”: “Answer”, “text”: “Yes. Tags and ordinary identifiers live in different name spaces in C, so typedef struct node { … } node; is legal. The same name then works both as struct node and as node. This is a C feature; C++ rules differ slightly.” } }, { “@type”: “Question”, “name”: “Does the Linux kernel use typedef struct?”, “acceptedAnswer”: { “@type”: “Answer”, “text”: “The kernel coding style discourages new typedefs for plain structures, mainly because they hide the fact that a type is a struct. Bare-metal firmware and many RTOS code bases use them heavily for readability. Follow the style of the code base you are working in.” } }, { “@type”: “Question”, “name”: “Is typedef struct in C the same as a #define macro?”, “acceptedAnswer”: { “@type”: “Answer”, “text”: “No. A typedef is processed by the compiler and obeys scope and type rules. A macro is plain text substitution done by the preprocessor, which is why macros fail for pointer types and for declaring several variables in one line.” } }, { “@type”: “Question”, “name”: “Does typedef affect memory usage or speed?”, “acceptedAnswer”: { “@type”: “Answer”, “text”: “No. A typedef only creates a name. The generated machine code is identical with or without it.” } } ] }
💬 Need help or career guidance? Ask us!Contact Us →

Leave a Reply

Your email address will not be published. Required fields are marked *

×

🚀 BLE on Linux (BlueZ)

Hands-on course. Only ₹399

Enroll Now →