C Preprocessor and Macros

C Preprocessor and Macros

In this chapter you will be introduced to the C preprocessor and macros . Besides, you will learn to use pre-processors like conditional, pragma, line control etc. in your program.

C preprocessors are macro preprocessors that allow you to define preprocessors in your program and that transform your program before compiling. This transformation may include header files, macro extensions, etc.

#All preprocessors begin with the directive symbol.

				
					#define PI 3.14

				
			

Attaching the header file

#includeC programs add pre-processors for attaching header files . For example:

				
					#include <stdio.h>

				
			

Here "stdio.h"is the header file. which consists of function and macro definitions. #includeThe pre-processor directive stdio.hreplaces the above line with the contents of the header file.

scanf()And that’s the main reason to use a preprocessor printf()before using a function .#include <stdio.h>

You can also create your own header files containing various function definitions and include them in your program using preprocessor directives.

C #if, #elif, #else, #endif pre-processors

These preprocessor directives create conditional parameters for compiling the source code that control the compilation of the source code. They must start on different lines.

syntax

				
					#if constant_expression
#else constant_expression
#endif

				
			

or

				
					
#if constant_expression
#elif constant_expression
#endif


				
			
  • If and only if the value of the #if expression is true (non-zero) then the compiler compiles the following codes.
  • But if the value of the #if expression is false(0) then the compiler skips the lines up to the next #else, #elif or #endif.
  • Lines between #else and #endif are compiled if the #if expression evaluates to false(0) and any #else evaluates to true(non-zero).
  • Lines between #elif and #endif are compiled if the value of #if expression is false(0) and if the constant_expression of an #elif is true(non-zero).

Example 1:

				
					int main(void)
 {
  #if 1
    printf("Hello SATT!\n");
  #else
    printf("Hello Aziz!\n");
  #endif
  return 0;
}
				
			

output

				
					"Hello SATT!"

				
			

In the above example only “Hello SATT!” has been printed. Because the value of #if is 1, the compiler skips the following codes.

Example 2:

				
					int main(void)
 {
  #if 1
    printf("Mango\n");
  #elif 1
    printf("Orange\n");
  #endif
  return 0;
}
				
			

output

				
					"Mango"

				
			

Here too only “Mango” is printed. Because only if the first line #if is 0 then “Orange” will be printed.

Example 3:

				
					#if OS==1
  printf("Version 1.0");
#elif OS==2
  printf("Version 2.0");
#else
  printf("Version unknown");
#endif
				
			

will be printed based on the OS setting and defined by the #define preprocessor.

C #define, #undef, #ifdef, #ifndef pre-processors

#define and #undef preprocessor directives agree to define identifiers that carry specific values. These identifiers can usually be constants or macro functions.

The #ifdef and #ifndef directives allow a specified number of lines of code to be compiled based on the condition that the identifier is defined.

syntax

				
					#define identifier replacement-code

#undef identifier

#ifdef identifier
#else or #elif
#endif

#ifndef identifier
#else or #elif
#endif

				
			
  • #ifdef identifier and #if defined( identifier) ​​are used in the same sense.
  • #ifndef identifier and #if !defined(identifier) ​​are used in the same sense.
  • An identifier defined by #define exists anywhere in the source code until #undef is reached.

Macro functions can be defined by #define in the following ways:

				
					#define identifier(parameter-list) (replacement-text)
				
			

The value of parameter-list is replaced by the value of replacement-text.

Example 1:

				
					#define PI 3.141
printf("%f",PI);

#define DEBUG
#ifdef DEBUG
  printf("This is a debug message.");
#endif

#define QUICK(x) printf("%s\n",x);
QUICK("Hi!")

#define ADD(x, y) x + y
z=3 * ADD(4,5)
				
			

The output of the above program will be 17. Because the work of guna takes place before addition.

Example 2:

				
					#define ADD(x,y) (x + y)
z=3 * ADD(4,5)
				
			

The output of the above program will be 17. Because sum is enclosed in parentheses and parentheses take precedence over multiplication.

C #include directive

External header files can be processed by the compiler through the #include directive.

syntax

				
					#include <header-file>

or

#include "source-file"
				
			

When a file is enclosed between < and > , the compiler (implementation) searches the known header directory (defined by compile) for that file and compiles it.

When the file is enclosed in double quotes, the entire content of the source-file is replaced. This search method for files is implementation-specific.

Example:

				
					#include <stdio.h>
#include "my_header.h"
				
			

C#line pre-processor

The #line directive allows changing the current line number and the current source code file name.

syntax

				
					#line line-number filename
				
			

Note that if no file name is given, it remains the same. The line number of the current line is one before the new line. So the first line is number 1.

Example:

				
					#line 50 user.c
#line 23
				
			

C #error pre-processor

The #error directive stops compilation and returns the specified error message.

syntax

				
					#error message
				
			

Example:

				
					#ifndef VERSION
#error Version number not specified.
#endif

				
			

C #pragma pre-processor

The #pragma directive allows defining directives. It controls the behavior of the compiler. If the pragma does not support it, it is skipped.

syntax

				
					#pragma directive
				
			

C macro

Macro (macro) is a fragment of code (a fragment of code) which is given a specific name. You can use this code fragment in your program by using the name.

Predefined macros

The following macros are already defined in the compiler and cannot be changed.

Predefined macrosdescription
__LINE__Integer constant to indicate the current line number
__FILE__The name of the executable source code file is the string for the directive
__DATE__String indicating the start date of compilation of the current source file. This is exactly the same format as the asctime function returns the date. eg “mmm dd yyyy”.
__TIME__String for the directive when compiling the running source file. This is exactly the same format as the asctime function returns the date. eg “hh:mm:ss”.
__STDC__If following the ANSI standard, the value will be 1 (non-zero).

Example:

C program for determining running time using predefined macros

				
					#include <stdio.h>
int main()
{
printf("Current time: %s",__TIME__); // Determine the current time
}
				
			

Output

				
					Current time: 19:54:39

				
			

7 Comments

  1. Love this blog! The content is always so relevant and insightful, keep up the great work!

  2. # Harvard University: A Legacy of Excellence and Innovation

    ## A Brief History of Harvard University

    Founded in 1636, **Harvard University** is the oldest and one of the most prestigious higher education institutions in the United States.
    Located in Cambridge, Massachusetts, Harvard has built a global reputation for academic excellence, groundbreaking research,
    and influential alumni. From its humble beginnings as a small college
    established to educate clergy, it has evolved into a world-leading
    university that shapes the future across various disciplines.

    ## Harvard’s Impact on Education and Research

    Harvard is synonymous with **innovation and intellectual leadership**.
    The university boasts:

    – **12 degree-granting schools**, including the renowned **Harvard Business School**, **Harvard Law School**, and **Harvard Medical School**.

    – **A faculty of world-class scholars**, many of whom are Nobel laureates, Pulitzer
    Prize winners, and pioneers in their fields.

    – **Cutting-edge research**, with Harvard leading initiatives in artificial intelligence, public health, climate change,
    and more.

    Harvard’s contribution to research is immense, with billions of dollars allocated to scientific discoveries and technological
    advancements each year.

    ## Notable Alumni: The Leaders of Today and Tomorrow

    Harvard has produced some of the **most influential figures** in history,
    spanning politics, business, entertainment, and
    science. Among them are:

    – **Barack Obama & John F. Kennedy** – Former U.S. Presidents
    – **Mark Zuckerberg & Bill Gates** – Tech visionaries (though Gates did not graduate)
    – **Natalie Portman & Matt Damon** – Hollywood icons

    – **Malala Yousafzai** – Nobel Prize-winning activist

    The university continues to cultivate future leaders who shape industries
    and drive global progress.

    ## Harvard’s Stunning Campus and Iconic Library

    Harvard’s campus is a blend of **historical charm and modern innovation**.

    With over **200 buildings**, it features:

    – The **Harvard Yard**, home to the iconic **John Harvard Statue** (and the famous
    “three lies” legend).
    – The **Widener Library**, one of the largest university libraries in the world, housing **over 20 million volumes**.

    – State-of-the-art research centers, museums, and performing arts
    venues.

    ## Harvard Traditions and Student Life

    Harvard offers a **rich student experience**, blending academics with vibrant traditions, including:

    – **Housing system:** Students live in one of 12 residential
    houses, fostering a strong sense of community.
    – **Annual Primal Scream:** A unique tradition where students de-stress by running through Harvard Yard
    before finals!
    – **The Harvard-Yale Game:** A historic football rivalry that unites alumni and students.

    With over **450 student organizations**, Harvard students engage in a diverse range
    of extracurricular activities, from entrepreneurship to
    performing arts.

    ## Harvard’s Global Influence

    Beyond academics, Harvard drives change in **global policy, economics, and technology**.
    The university’s research impacts healthcare, sustainability,
    and artificial intelligence, with partnerships across industries worldwide.
    **Harvard’s endowment**, the largest of any university, allows it to
    fund scholarships, research, and public initiatives, ensuring a legacy
    of impact for generations.

    ## Conclusion

    Harvard University is more than just a school—it’s a
    **symbol of excellence, innovation, and leadership**.
    Its **centuries-old traditions, groundbreaking discoveries, and transformative education** make it one of the most influential institutions in the world.
    Whether through its distinguished alumni, pioneering research,
    or vibrant student life, Harvard continues to shape the future in profound ways.

    Would you like to join the ranks of Harvard’s legendary scholars?

    The journey starts with a dream—and an application!

    https://www.harvard.edu/

  3. Your positivity and optimism are contagious It’s impossible to read your blog without feeling uplifted and inspired Keep up the amazing work

Leave a Reply

Your email address will not be published. Required fields are marked *