1. Introduction
In C programming, structures (struct) are used to group different data types into a single unit. The typedef keyword, when used with structures, creates a new name or alias for the structure, simplifying the syntax for declaring variables of that structure type.
2. Key Points
1. struct is used to define a new data structure with more than one member.
2. typedef struct allows the creation of an alias for the structure type.
3. Without typedef, you must use the keyword struct every time you declare a variable of that structure type.
4. With typedef, you can use the alias as the type name without the struct keyword.
3. Differences
struct | typedef struct |
---|---|
Requires struct keyword in variable declarations. | Allows using an alias for the structure type without the struct keyword. |
Syntax can be more verbose. | Simplifies the syntax for using the structure type. |
4. Example
#include <stdio.h>
// Using struct
struct Person {
char name[50];
int age;
};
// Using typedef struct
typedef struct {
char name[50];
int age;
} PersonAlias;
int main() {
struct Person person1;
PersonAlias person2;
person1.age = 30;
person2.age = 25;
printf("person1 age: %d\n", person1.age);
printf("person2 age: %d\n", person2.age);
return 0;
}
Output:
person1 age: 30 person2 age: 25
Explanation:
1. person1 is declared with struct Person. The struct keyword is required.
2. person2 is declared using PersonAlias. The typedef creates an alias so struct is not needed.
5. When to use?
- Use struct when you're working with simple structures and don't mind the additional verbosity.
- Use typedef struct for a cleaner and more readable code, especially when the structure is used frequently or the structure name is long.
Difference between malloc() and calloc()?
Difference between Local Variable and Global Variable in C
Difference between Global and Static Variables in C
Difference Between Call by Value and Call by Reference in C
Difference Between getch() and getche() in C
Difference between printf() and sprintf() in C
Difference between Arrays and Pointers in C
Difference between Structure and Union in C
Difference Between Stack and Heap Memory Allocation in C
Difference Between Macro and Function in C
Difference between = and == in C
Difference Between for loop and while loop in C
Difference Between Linked List and Array in C
Difference between fgets() and gets() in C
Difference between ++i and i++ in C
Difference between struct and typedef struct in C
Difference between int main() and void main() in C
Difference between Character Array and String in C
Comments
Post a Comment
Leave Comment