Table of Contents

Lab 06 - Structs and enums

Structs

struct Point {
    int x;
    int y;
};
 
struct Point p = {10, 20};
printf("%d %d", p.x, p.y);

typedef struct {
    char name[20];
    int age;
} Person;

Unions

union Number {
    int i;
    float f;
    char c;
};
 
union Number n;
n.f = 3.14;
printf("%f", n.f);

Enums

enum Color { RED, GREEN = 5, BLUE };
enum Color c = BLUE;
printf("%d\n", c);  // prints 6

Bit Fields

struct Status {
    unsigned int power : 1;
    unsigned int error : 1;
    unsigned int mode  : 2; // 0–3
};

Preprocessor

      #define SQUARE(x) ((x)*(x))  // OK
      #define SQUARE(x) (x*x)  // WRONG

#define PI 3.14159
#define SQUARE(x) ((x)*(x))
#define DEBUG
 
#ifdef DEBUG
  printf("Debug mode on\n");
#endif


Task 1: Struct + Enum

Create a program that defines:

enum Department { IT, HR, SALES };
struct Employee {
    char name[30];
    int age;
    enum Department dept;
};

Task 2: Union + Bit Fields

Define a union for storing a 32-bit register as either:

struct {
    unsigned int enable   : 1;
    unsigned int mode     : 2;
    unsigned int error    : 1;
    unsigned int reserved : 28;
};

Your program will:

Task 3: Preprocessor + Conditional Compilation

Use a macro for debug control:

#define DEBUG 1

#ifdef DEBUG
    printf("[DEBUG] Value = %d\n", x);
#endif