Structures and Unions in C

 Structures and Unions in C


Structures and unions allow you to create custom data types that can hold multiple values of different types. Structures are used to group related data, while unions enable you to store different data types in the same memory location.


#include <stdio.h>


struct Rectangle {

    int width;

    int height;

};


union Number {

    int intValue;

    float floatValue;

    char stringValue[10];

};


int main() {

    struct Rectangle rect;

    rect.width = 5;

    rect.height = 3;


    printf("Rectangle: width = %d, height = %d\n", rect.width, rect.height);


    union Number num;

    num.intValue = 10;

    printf("Integer value: %d\n", num.intValue);


    num.floatValue = 3.14;

    printf("Float value: %.2f\n", num.floatValue);


    strcpy(num.stringValue, "Hello");

    printf("String value: %s\n", num.stringValue);


    return 0;

}

In this example, a structure Rectangle is defined to hold width and height values. A union Number is also defined to store different types of values. The program demonstrates

No comments:

Post a Comment

The Importance of Cybersecurity in the Digital Age

 The Importance of Cybersecurity in the Digital Age Introduction: In today's digital age, where technology is deeply intertwined with ev...