Monday, April 28, 2025

C Tutorial - 22 - Unions

What are Unions in C and why do we need it them

In C, a union is a special data type that allows you to store different data types in the same memory location. It is similar to a structure, but only one member can be accessed at a time. Unions are useful when you need to store different data types in the same memory location, but you don't need to access more than one member at a time.

The size of a union is determined by the size of its largest member. When you create a union, the memory for all its members is allocated in a single block. This means that if you change the value of one member, the value of the other members may also change.

Unions are useful when you need to store different types of data in a small amount of memory. For example, in a program that works with both integers and floating-point numbers, you can define a union that has both an integer member and a floating-point member. This allows you to store either an integer or a floating-point number in the same memory location, depending on which member you access.Here's an example of a union in C:

#include <stdio.h>

union Data {
   int i;
   float f;
   char str[20];
};

int main() {
   union Data data;

   data.i = 10;
   printf( "data.i : %d\n", data.i);

   data.f = 220.5;
   printf( "data.f : %f\n", data.f);

   strcpy( data.str, "C Programming");
   printf( "data.str : %s\n", data.str);

   return 0;
}

In this example, we define a union Data that has three members: an integer i, a floating-point number f, and a character array str. We create a variable data of type Data and set its i member to 10, then print it. We then set its f member to 220.5, and print it. Finally, we set its str member to "C Programming", and print it. Note that each time we set a member, the value of the previous member is overwritten.

 

Union in C Example

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

union Rectangle
{
    int x;
    int y;
    char name[50];
};

int main()
{

    union Rectangle first;

    first.x = 10;
    printf("X: %d \n", first.x);

    first.y = 20;
    printf("Y: %d \n", first.y);

    strcpy(first.name, "First Rectangle");
    printf("Name: %s \n", first.name);

    return 0;
}

Result:

X: 10
Y: 20
Name: First Rectangle

Process returned 0 (0x0)   execution time : 0.000 s
Press any key to continue.

This code declares a union named Rectangle with three members: x, y, and name. In the main() function, it declares a variable first of type Rectangle.

It then assigns a value of 10 to first.x and prints its value using printf(). It then assigns a value of 20 to first.y and prints its value using printf(). Finally, it assigns the string "First Rectangle" to first.name using strcpy() and prints its value using printf().

Since x, y, and name are all members of the same union, they share the same memory space. So when first.y is assigned a value of 20, it overwrites the previous value of 10 that was stored in first.x. Similarly, when strcpy() is used to assign the string to first.name, it overwrites the previous values of x and y. Therefore, only one member of the union can be used at a time.

 

Can we create Unions in External C file

Yes, we can create unions in external C files by defining the union in the header file and then including the header file in the source file where we want to use the union. The syntax for creating a union in an external file is the same as creating it in the same file. Here is an example of how to create a union in an external file:

Create a header file named shapes.h with the following content:

#ifndef SHAPES_H
#define SHAPES_H

union Shape {
    int x;
    int y;
    char name[50];
};

#endif

In the source file where we want to use the union, we include the shapes.h header file:

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

int main() {

    union Shape first;

    first.x = 10;
    printf("X: %d \n", first.x);

    first.y = 20;
    printf("Y: %d \n", first.y);

    strcpy(first.name, "First Shape");
    printf("Name: %s \n", first.name);

    return 0;
}

When we compile the source file, we need to include the header file in the compilation command.

 

What are lines #ifndef SHAPES_H, #define SHAPES_H and #endif

These lines are known as include guards, and they are commonly used in C and C++ header files to prevent multiple definitions of the same code.

#ifndef checks if the macro SHAPES_H is already defined. If it is not defined, then the code inside the #ifndef and #endif directives is compiled.

#define SHAPES_H defines the macro SHAPES_H so that it cannot be defined again. This is necessary to prevent multiple definitions of the same code.

#endif marks the end of the block of code that should only be included once.

 

What are Macros in C Programming

In C programming, a macro is a small piece of code or a symbol that is defined by the programmer to represent a larger piece of code. Macros are defined using the #define preprocessor directive.

The main purpose of macros is to simplify code and reduce typing by allowing the programmer to define commonly used code as a single statement. Macros can be used for various purposes such as defining constants, conditional compilation, and code generation.

Here's an example of how to define a macro in C: 

#define PI 3.14159265358979323846

This macro defines a constant value for PI, which can be used in the code by simply typing "PI" instead of the long decimal value.

Macros can also take arguments, like a function, and perform operations using those arguments. For example:

#define SQUARE(x) ((x) * (x))

This macro defines a function-like macro that takes an argument "x" and returns its square. In the code, this macro can be used as follows:

int num = 5;
int squared = SQUARE(num); // equivalent to (5 * 5)

Macros can be a powerful tool in C programming, but they should be used with caution. Improper use of macros can lead to code that is difficult to read and maintain.

No comments:

Post a Comment

Tkinter Introduction - Top Widget, Method, Button

First, let's make shure that our tkinter module is working ok with simple  for loop that will spawn 5 instances of blank Tk window .  ...