ScholarQuill logoScholarQuillUniversity Notes
My Semester
Explore Notes
Past Papers12 New
Video CoursesNew
Search
Settings
Study Tools
GPA/CGPA Calculator
Schedule & To-Do
Student Portal
Contact
Contact
ScholarQuill logo
My Semester
Explore Notes
Past Papers12 New
Video CoursesNew
Search
Settings
GPA/CGPA Calculator
Schedule & To-Do
Student Portal
Contact
ScholarQuill logoScholarQuillUniversity Notes
Study PortalCC-112Typedef Unions
Ctrl + K
Login
Explore
Search
Semester
Papers
CGPA
    CC-112

    Programming Fundamentals

    Progress0 / 39 done
    Topics39
    1Introduction to Problem Solving, Algorithms, Programming, and C Language2Problem Solving, a brief review of Von-Neumann Architecture3The C Programming Language, Pseudo-code, Concept of Variable4Data types in Pseudo-code, The C Standard Library and Open Source5Input/Output, Arithmetic expressions, Assignment statement, Operator precedence6Concept of Integer division, Flowchart and its notations7Typical C Program Development Environment, Role of Compiler and Linker8Test Driving C Application
    9A Simple C Program: Printing Text, Adding Two Integer10Memory Concepts, Arithmetic in C, Operators
    11Equality and Relational Operators
    12The if, if...else, while Nested Control Statements
    13for, switch, do...while, break, continue, Logical Operators
    14Modularizing Program in C, Math Library Functions15Function Definitions and Prototypes, Function-Call Stack and Stack Frames16Stack rolling and unrolling, Headers, Passing Arguments by Value and by Reference17Random Number Generation, Scope Rules, Recursion, Recursion vs Iteration
    18Defining Arrays, Character Arrays, Static and Automatic Local Arrays19Passing Arrays to Function, Sorting and Searching Arrays20Multidimensional and Variable Length Arrays
    21Pointer Definitions and Initialization, Pointer Operators22Passing Arguments to Function by Reference, Using the const and sizeof Operator23Pointer Expressions and Arithmetic, Pointers and Arrays, Array of Pointers24Function Pointers
    25Strings and Characters, Character Handling Library26String Functions, Library Functions
    27Streams, Formatted Output with printf, Formatted Input with scanf
    28Defining Structures, Accessing Structure Member, Structures and Functions29typedef, Unions
    30Bitwise Operators, Bit Fields, Enumeration Constants
    31Files and Streams, Creating, Reading and Writing data to a Sequential and a Random-Access File
    32#include, #define, Conditional Compilation, #error and #pragma33# and ## Operators, Predefined Symbolic Constants, Assertions
    34Variable Length Argument List, Using Command Line Arguments35Compiling Multiple-Source-File Programs, Program Termination with exit and atexit36Suffixes for Integer and Floating-Point Literals, Signal Handling
    37calloc and realloc, goto
    38Self-Referential Structures, Linked Lists39Efficiency of Algorithms, Selection and Insertion Sort
    7 min read
    Topic 29 of 39
    Topic Study Note Illustration
    29

    typedef, Unions

    In C, typedef and unions are powerful concepts that help improve code readability, organization, and flexibility. While typedef simplifies type definitions, unions allow storing different data types...

    typedef and Unions in C

    In C, typedef and unions are powerful concepts that help improve code readability, organization, and flexibility. While typedef simplifies type definitions, unions allow storing different data types in the same memory location, offering a memory-efficient way to handle multiple data types.

    Let's explore these concepts in detail.


    1. typedef in C

    The typedef keyword in C is used to create alias names for existing data types. It makes the code easier to read and manage, especially for complex data types like pointers, structures, or arrays.

    Syntax for typedef:

    typedef existing_type new_type_name;
    
    • existing_type: The original type (like int, float, struct, etc.).
    • new_type_name: The new name you want to give to the existing type.

    Why use typedef?

    • Simplifies complex declarations: Especially useful for pointers, structures, or function pointers.
    • Improves code readability: Makes the code more meaningful, especially when used with structures or pointers.
    • Improves maintainability: Changing the underlying type becomes easier because you only need to change it in one place.

    Example: Using typedef with basic types

    #include <stdio.h>
    
    typedef unsigned long ulong; // Defining an alias for unsigned long
    
    int main() {
        ulong largeNumber = 5000000000; // Now you can use 'ulong' instead of 'unsigned long'
        printf("Large number: %lu\n", largeNumber);
        return 0;
    }
    

    Explanation:

    • typedef unsigned long ulong; defines ulong as an alias for unsigned long.
    • Now you can use ulong to declare variables of type unsigned long.

    Output:

    Large number: 5000000000
    

    Example: Using typedef with Structures

    #include <stdio.h>
    
    typedef struct {
        char name[50];
        int age;
    } Person; // Define 'Person' as an alias for 'struct' with the given members
    
    int main() {
        Person p1 = {"Alice", 30}; // No need to write 'struct' before Person
        printf("Name: %s\nAge: %d\n", p1.name, p1.age);
        return 0;
    }
    

    Explanation:

    • typedef struct {...} Person; creates an alias Person for the structure.
    • You can now declare Person as if it were a simple type.

    Output:

    Name: Alice
    Age: 30
    

    Example: Using typedef with Function Pointers

    #include <stdio.h>
    
    typedef int (*operation)(int, int); // Define operation as a function pointer type
    
    int add(int a, int b) {
        return a + b;
    }
    
    int main() {
        operation op = add; // Using the 'operation' typedef to store the function
        int result = op(5, 3); // Calling the function through the pointer
        printf("Result: %d\n", result);
        return 0;
    }
    

    Explanation:

    • typedef int (*operation)(int, int); creates a typedef operation for a function pointer that takes two integers and returns an integer.
    • The function add is assigned to op, and the function is called using op.

    Output:

    Result: 8
    

    2. Unions in C

    A union in C allows multiple data types to share the same memory location. Only one member of a union can store a value at any given time. This can be useful when you need to store different types of data but don't need all the data at once, which saves memory.

    Syntax for Declaring a Union:

    union union_name {
        data_type1 member1;
        data_type2 member2;
        // Additional members
    };
    
    • union_name: Name of the union.
    • member1, member2, ...: Members of the union, which can be of different data types.

    Memory Allocation in a Union:

    The size of a union is determined by the size of its largest member. All members of a union share the same memory, so only one member can hold a value at any given time.

    Example: Defining and Using a Union

    #include <stdio.h>
    
    union Data {
        int i;
        float f;
        char str[20];
    };
    
    int main() {
        union Data data;
    
        // Assigning and printing an integer value
        data.i = 10;
        printf("data.i = %d\n", data.i);
    
        // Assigning and printing a float value
        data.f = 3.14;
        printf("data.f = %.2f\n", data.f);
    
        // Assigning and printing a string value
        strcpy(data.str, "Hello, Union!");
        printf("data.str = %s\n", data.str);
    
        // Notice that only the last assigned member is correctly stored
        printf("\nAfter Assigning String:\n");
        printf("data.i = %d\n", data.i);  // Will print garbage because the memory is shared
        printf("data.f = %.2f\n", data.f); // Will print garbage
    
        return 0;
    }
    

    Explanation:

    • The union Data has three members: an integer i, a float f, and a string str.
    • After each assignment (data.i = 10, data.f = 3.14, data.str = "Hello, Union!"), only the last assigned value will be correctly stored, as all members of the union share the same memory location.

    Output:

    data.i = 10
    data.f = 3.14
    data.str = Hello, Union!
    
    After Assigning String:
    data.i = 0
    data.f = 0.00
    

    Key Points:

    • Memory Sharing: The union allows memory to be shared among its members. This means that only one member can store a value at a time.
    • Size of a Union: The size of the union is determined by the size of its largest member. In the above example, the size of union Data will be the size of the str array (since it's the largest member, typically 20 bytes).
    • Use Case: Unions are useful when different types of data are required in the same memory space but at different times, such as when handling different types of data that may be used in a particular situation.

    3. Comparison Between typedef and Unions

    Feature typedef Unions
    Purpose Provides an alias for an existing data type. Allows multiple data types to share the same memory space.
    Memory Does not affect memory allocation; just an alias. All members share the same memory location, only one can hold a value at a time.
    Use Case Simplifies complex data types and improves readability. Saves memory when you need to store different data types, but only one at a time.
    Example typedef int MyInt; union Data { int i; float f; char str[20]; };

    4. Conclusion

    • typedef is useful for simplifying the code and improving readability by giving existing types more meaningful names, especially for complex types like structures or function pointers.

    • Unions provide a way to store multiple types of data in the same memory location, saving memory when you need to use different types of data at different times, but never at the same time.

    Both features make your code more readable and efficient, helping to manage complex data structures and memory usage effectively.

    ← Previous topic 28
    Structures: Defining Structures, Accessing Structure Member, Structures and Functions
    Next topic 30 →
    Bit Manipulation and Enumeration: Bitwise Operators, Bit Fields, Enumeration Constants

    Past Papers

    Open this section to view and download past papers

    Click on Show Past Papers to load available exam papers.

    Reading Progress
    0%
    7mremaining
    1.1kwords
    Intermediatelevel
    On This Page

    No headings found

    Study Toolkit

    Subject Portal

    Programming Fundamentals