Chapter 15: Advanced Topics (Introduction)

These are the features that make C a very powerful and flexible language. Most beginners skip them, but once you understand these, you can write professional-level code, make your programs more efficient, and understand real-world C code (like Linux kernel or game engines).

We will cover:

  • Preprocessor directives
  • Macros
  • Enums
  • Bit fields
  • Typedef
  • Command-line arguments

Let’s go one by one.

1. Preprocessor Directives

These are instructions for the preprocessor (the first stage of compilation). They start with # and are processed before the actual compilation.

Common directives:

#include – Include header files

C

#define – Define constants or macros

C

#undef – Undefine a previously defined macro

C

#ifdef / #ifndef / #endif – Conditional compilation

C

#if / #else / #elif – More advanced conditions

C

2. Macros

Macros are like text replacements done by the preprocessor.

Simple constant macro

C

Function-like macro (very powerful!)

C

Best practice: Always put parentheses around arguments and whole expression – prevents bugs!

Bad macro (can cause wrong result):

C

3. Enums (Enumerations)

Enums let you create a set of named integer constants – makes code readable.

Syntax:

C

Example – Days of the week

C

Output:

text

4. Bit Fields

Bit fields let you pack multiple small integer values into one integer – saves memory.

Syntax:

C

Example – Packing student flags

C

Use cases:

  • Network packets
  • Hardware registers
  • Flags in embedded systems

5. Typedef

typedef creates an alias (new name) for existing data types – makes code cleaner.

Syntax:

C

Examples:

C

Very common in real code:

C

6. Command-Line Arguments

Your program can accept arguments when you run it from terminal/command prompt.

Syntax in main():

C
  • argc = argument count (including program name)
  • argv = array of strings (argument values)

Example:

C

How to run:

Bash

Output:

text

Real use:

  • ./calculator 10 + 20 → argv[1] = “10”, argv[2] = “+”, argv[3] = “20”

Today’s Homework

  1. Create a macro MAX(a,b) that returns the larger of two numbers.
  2. Define an enum for months (JAN to DEC) and print the month name based on user input.
  3. Use typedef to create alias for a structure Employee (name, id, salary).
  4. Write a program that uses command-line arguments to add two numbers (e.g., ./add 15 25 should print 40).
  5. Create a structure with bit fields for flags (like isAdmin:1, isActive:1, role:3) and print their values.

You may also like...