ScholarQuill logoScholarQuillUniversity Notes
  • Notes
  • Past Papers
  • Blogs
  • Todo
Login
ScholarQuill logoScholarQuillUniversity Notes
Login
NotesPast PapersBlogsTodo
More
SubjectsDiscussionCGPA CalculatorGPA CalculatorStudent PortalCourse Outline
About
About usPrivacy PolicyReportContact
Notes
Past Papers
Blogs
Todo
Analytics
    Current Subject
    🧩
    Programming Fundamentals
    CC-112
    Progress0 / 39 topics
    Topics
    1. Introduction to Problem Solving, Algorithms, Programming, and C Language2. Problem Solving, a brief review of Von-Neumann Architecture3. The C Programming Language, Pseudo-code, Concept of Variable4. Data types in Pseudo-code, The C Standard Library and Open Source5. Input/Output, Arithmetic expressions, Assignment statement, Operator precedence6. Concept of Integer division, Flowchart and its notations7. Typical C Program Development Environment, Role of Compiler and Linker8. Test Driving C Application9. Introduction to C Programming: A Simple C Program: Printing Text, Adding Two Integer10. Memory Concepts, Arithmetic in C, Operators11. Decision Making: Equality and Relational Operators12. Structured Program Development: The if, if...else, while Nested Control Statements13. Program Control: for, switch, do...while, break, continue, Logical Operators14. Functions: Modularizing Program in C, Math Library Functions15. Function Definitions and Prototypes, Function-Call Stack and Stack Frames16. Stack rolling and unrolling, Headers, Passing Arguments by Value and by Reference17. Random Number Generation, Scope Rules, Recursion, Recursion vs Iteration18. Arrays: Defining Arrays, Character Arrays, Static and Automatic Local Arrays19. Passing Arrays to Function, Sorting and Searching Arrays20. Multidimensional and Variable Length Arrays21. Pointers: Pointer Definitions and Initialization, Pointer Operators22. Passing Arguments to Function by Reference, Using the const and sizeof Operator23. Pointer Expressions and Arithmetic, Pointers and Arrays, Array of Pointers24. Function Pointers25. Characters and Strings: Strings and Characters, Character Handling Library26. String Functions, Library Functions27. Formatted Input/Output: Streams, Formatted Output with printf, Formatted Input with scanf28. Structures: Defining Structures, Accessing Structure Member, Structures and Functions29. typedef, Unions30. Bit Manipulation and Enumeration: Bitwise Operators, Bit Fields, Enumeration Constants31. File Processing: Files and Streams, Creating, Reading and Writing data to a Sequential and a Random-Access File32. Preprocessor: #include, #define, Conditional Compilation, #error and #pragma33. # and ## Operators, Predefined Symbolic Constants, Assertions34. Other Topics: Variable Length Argument List, Using Command Line Arguments35. Compiling Multiple-Source-File Programs, Program Termination with exit and atexit36. Suffixes for Integer and Floating-Point Literals, Signal Handling37. Dynamic Memory Allocation: calloc and realloc, goto38. Advance Topics: Self-Referential Structures, Linked Lists39. Efficiency of Algorithms, Selection and Insertion Sort
    CC-112›typedef, Unions
    Programming FundamentalsTopic 29 of 39

    typedef, Unions

    7 minread
    1,109words
    Intermediatelevel

    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 load past papers

    Click on Show Past Papers to see past papers.
    On This Page
      Reading Stats
      Est. reading time7 min
      Word count1,109
      Code examples0
      DifficultyIntermediate