C typedef

C typedef: Creating Custom Data Type Names

The typedef keyword in C is used to assign a new, alternative name to an existing data type. This is incredibly useful for making your code more readable, reducing complexity (especially with pointers and structs), and improving code portability across different systems.

Why use typedef?


1. Using typedef with Basic Types

You can use typedef to create aliases for standard primitive types. This is common in systems programming to define types with specific sizes (like uint32_t).

Basic typedef Example:

#include <stdio.h>

// Creating an alias for unsigned long long typedef unsigned long long ULL;

int main() { // Using the new alias to declare a variable ULL hugeNumber = 18446744073709551615ULL; printf("The huge number is: %llu\n", hugeNumber); return 0; }


2. Using typedef with Structs

The most common and practical use of typedef is with structs. Normally, every time you declare a struct variable, you must use the struct keyword. typedef allows you to treat the struct like a built-in type.

typedef with Struct Example:

#include <stdio.h>
#include <string.h>

// Defining a struct and its alias simultaneously typedef struct { char name[50]; int age; float gpa; } Student;

int main() { // Notice we don't need to write 'struct Student' Student student1; strcpy(student1.name, "Alice"); student1.age = 20; student1.gpa = 3.8; printf("Student: %s, Age: %d, GPA: %.1f\n", student1.name, student1.age, student1.gpa); return 0; }


Exercise

?

Which of the following statements about typedef is TRUE?