The Wayback Machine - https://web.archive.org/web/20241115023207/https://www.geeksforgeeks.org/define-preprocessor-in-cpp/
Open In App

#define in C++

Last Updated : 14 May, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In C++, #define is a preprocessor directive used to define a macro. Macros are a way to represent a fragment of code or a constant value by giving it a name. When the preprocessor encounters the macro name in the code, it replaces it with the corresponding code fragment or value that is defined using the #define preprocessor. In this article we will learn about using #define in C++.

Syntax of #define in C++

We can define the two types of macro using #define:

  1. Constant Macros
  2. Chain Macros
  3. Macro Expressions
  4. Multiline Macros

Syntax for Defining Constant Macros

#define MACRO_NAME value

They are also called object-like macros by a number of people.

Syntax for Defining Chain Macros

#define MACRO1_NAME  value1
#define value1 final_value

Syntax for Defining Expression Macros

#define MACRO_NAME (expression within brackets)

We can also define a macro expression that takes parameters:

#define MACRO_NAME(parameters)  (expression)

These types of macros are also called function like macros.

Syntax for Defining Multiline Macros

The backslash (\) here works as the joiner of the two values.

#define MACRO_NAME value \
value2 \
value3 \

Examples of #define in C++

Example 1: Macro Constant

In the following example we have used #define to assign a constant value to PI so that PI can be referred later in the program to calculate the area of the circle.

C++
// C++ Program to calculate the area of the circle with a
// predefined macro
#include <iostream>
using namespace std;

#define PI 3.1425

int main()
{
    float radius = 5, area;
    cout << "Enter the radius of a circle: ";
    cin >> radius;

    area = PI * (radius * radius);

    cout << "\nArea = " << area;
    cout << endl;

    return 0;
}

Output
Enter the radius of a circle: 
Area = 78.5625

Example 2: Macro Expression

In the following example we have used #define to define a for loop expression that will print the values present in an array.

C++
// C++ Program for to illustrate how to use function like or
// expression macros
#include <iostream>
#include <string>
using namespace std;

// defining short expression of for loop
#define forLoop(len) for (int i = 0; i < len; i++)

int main()
{
    string arr[5]
        = { "Geeks", "for", "Geeks", "C++", "Tutorial" };

    forLoop(5) { cout << arr[i] << "\n"; }
    return 0;
}

Output
Geeks
for
Geeks
C++
Tutorial

Example 3: Chain Macros

C++
// C++ Program to illustrate how to use chain like macros
#include <iostream>

// defining one macro that has value which in turn is
// another macro
#define ALL_USERS FB_USERS
// macro linked to upper macro
#define FB_USERS 100

using namespace std;

int main()
{

    cout << "ALL_USERS: " << ALL_USERS;

    return 0;
}

Output
ALL_USERS: 100

Example 4: Multiline Macros

C++
// C++ program to illustrate how to use multiline macros
#include <iostream>

// defining a multiline string that will be joined when it
// is used in the program
#define SENTENCE "Welcome \
to \
GeeksforGeeks"

using namespace std;

int main()
{
    cout << SENTENCE;
  
    return 0;
}

Output
Welcome to GeeksforGeeks

Properties of #define Macros

The following are some important properties of macros:

  1. Macros are like labels and not like variable names, we cannot reassing them any value later on in the program.
  2. Macros' values are substituted in the program in the preprocessing phase.
  3. Macro defined using the #define can be undefined using #undef.
  4. We can also check if the macro name is defined using #ifdef and #ifndef.

Applications of #define in C++

Following are some applications of #define:

  • #define is commonly used to define constants that are replaced by their values during preprocessing.
  • Used to define simple macros that removes the repetitive code from the program.
  • Used for conditional compilation to include or exclude certain sections of code based on specific conditions.
  • Used to shorten lengthy expression present in the program.

One of the major application of Macros in C was in the generic programming but it is not required in C++ as C++ have templates for generic programming.


Similar Reads

C++ set for user define data type
The C++ STL set is a data structure used to store the distinct value in ascending or descending order. By default, we can use it to store system defined data type only(eg. int, float, double, pair etc.). And if we want to store user-defined datatype in a set (eg. structure) then the compiler will show an error message. That is because of the proper
2 min read
C++ map having key as a user define data type
C++ map stores keys in ordered form (Note that it internally use a self balancing binary search tree). Ordering is internally done using operator " < " So if we use our own data type as key, we must overload this operator for our data type. Let us consider a map having key data type as a structure and mapped value as integer. // key's struc
3 min read
“static const” vs “#define” vs “enum”
In this article, we will be analyzing "static const", "#define" and "enum". These three are often confusing and choosing which one to use can sometimes be a difficult task. static const static const : "static const" is basically a combination of static(a storage specifier) and const(a type qualifier). Static : determines the lifetime and visibility
4 min read
How to Define the Constructor Outside the Class in C++?
A constructor is a special type of member function whose task is to initialize the objects of its class. It has no return type so can't use the return keyword and it is implicitly invoked when the object is created. Constructor is also used to solve the problem of initialization. It is called after the object is created.Same name as of class. Const
2 min read
How to Define Constants in C++?
In C++, constants are the tokens that are used to represent those values that cannot be changed during the program execution. It is defined only once and remains the same throughout the execution of the program. C++ provides various different methods to define constants. In this article, we will discuss such methods to define constants and see how
4 min read
C++ Programming Language
C++ is the most used and most popular programming language developed by Bjarne Stroustrup. C++ is a high-level and object-oriented programming language. This language allows developers to write clean and efficient code for large applications and software development, game development, and operating system programming. It is an expansion of the C pr
9 min read
30 OOPs Interview Questions and Answers (2024) Updated
Object-oriented programming, or OOPs, is a programming paradigm that implements the concept of objects in the program. It aims to provide an easier solution to real-world problems by implementing real-world entities such as inheritance, abstraction, polymorphism, etc. in programming. OOPs concept is widely used in many popular languages like Java,
15+ min read
Top 50 C++ Project Ideas For Beginners & Advanced
C++ is one of the most popular programming languages widely used in the software industry for projects in different domains like games, operating systems, web browsers, DBMS, etc due to its fast speed, versatility, lower-level memory access, and many more. Many top companies like Microsoft, Google, Apple, Netflix, etc use C++ to develop their produ
15+ min read
C++ Programming Examples
Writing C++ programs yourself is the best way to learn the C++ language. C++ programs are also asked in the interviews. This article covers the top practice problems for basic C++ programs on topics like control flow, patterns, and functions to complex ones like pointers, arrays, and strings. C++ Tutorial C++ Recent Articles Topics: Basic Programs
9 min read
C++ Interview Questions and Answers (2024)
C++ - the must-known and all-time favourite programming language of coders. It is still relevant as it was in the mid-80s. As a general-purpose and object-oriented programming language is extensively employed mostly every time during coding. As a result, some job roles demand individuals be fluent in C++. It is utilized by top IT companies such as
15+ min read
Left Shift and Right Shift Operators in C/C++
In C/C++, left shift (<<) and right shift (>>) operators are binary bitwise operators that are used to shift the bits either left or right of the first operand by the number of positions specified by the second operand allowing efficient data manipulation. In this article, we will learn about the left shift and right shift operators. Le
6 min read
Virtual Function in C++
A virtual function (also known as virtual methods) is a member function that is declared within a base class and is re-defined (overridden) by a derived class. When you refer to a derived class object using a pointer or a reference to the base class, you can call a virtual function for that object and execute the derived class's version of the meth
6 min read
Inheritance in C++
The capability of a class to derive properties and characteristics from another class is called Inheritance. Inheritance is one of the most important features of Object Oriented Programming in C++. In this article, we will learn about inheritance in C++, its modes and types along with the information about how it affects different properties of the
15+ min read
C++ Polymorphism
The word "polymorphism" means having many forms. In simple words, we can define polymorphism as the ability of a message to be displayed in more than one form. A real-life example of polymorphism is a person who at the same time can have different characteristics. A man at the same time is a father, a husband, and an employee. So the same person ex
7 min read
C++ Classes and Objects
In C++, classes and objects are the basic building block that leads to Object-Oriented programming in C++. In this article, we will learn about C++ classes, objects, look at how they work and how to implement them in our C++ program. What is a Class in C++?A class is a user-defined data type, which holds its own data members and member functions, w
10 min read
Decision Making in C (if , if..else, Nested if, if-else-if )
The conditional statements (also known as decision control structures) such as if, if else, switch, etc. are used for decision-making purposes in C programs. They are also known as Decision-Making Statements and are used to evaluate one or more conditions and make the decision whether to execute a set of statements or not. These decision-making sta
11 min read
C++ Data Types
All variables use data type during declaration to restrict the type of data to be stored. Therefore, we can say that data types are used to tell the variables the type of data they can store. Whenever a variable is defined in C++, the compiler allocates some memory for that variable based on the data type with which it is declared. Every data type
11 min read
std::sort() in C++ STL
std::sort() is an STL function that is used to sort the given range in desired order. It provides a simple and efficient way to sort the data in C++ but it only works on data structure which have random access to its elements such as vectors and arrays. It is defined inside <algorithm> header file. Syntaxstd::sort (first, last, comp);Paramete
4 min read
Priority Queue in C++ Standard Template Library (STL)
A C++ priority queue is a type of container adapter, specifically designed such that the first element of the queue is either the greatest or the smallest of all elements in the queue, and elements are in non-increasing or non-decreasing order (hence we can see that each element of the queue has a priority {fixed order}). In C++ STL, the top elemen
11 min read
Vector in C++ STL
Vectors are the same as dynamic arrays with the ability to resize themselves automatically when an element is inserted or deleted, with their storage being handled automatically by the container. Vector elements are placed in contiguous storage so that they can be accessed and traversed using iterators. In vectors, data is inserted at the end. Inse
11 min read
Map in C++ Standard Template Library (STL)
Maps are associative containers that store elements in a mapped fashion. Each element has a key value and a mapped value. No two mapped values can have the same key values. std::map is the class template for map containers and it is defined inside the <map> header file. Basic std::map Member FunctionsSome basic functions associated with std::
9 min read
C++ Standard Template Library (STL)
The C++ Standard Template Library (STL) is a set of template classes and functions that provides the implementation of common data structures and algorithms such as lists, stacks, arrays, sorting, searching, etc. It also provides the iterators and functors which makes it easier to work with algorithms and containers. STL was originally designed by
9 min read
Object Oriented Programming in C++
Object-oriented programming - As the name suggests uses objects in programming. Object-oriented programming aims to implement real-world entities like inheritance, hiding, polymorphism, etc. in programming. The main aim of OOP is to bind together the data and the functions that operate on them so that no other part of the code can access this data
10 min read
Copy Constructor in C++
A copy constructor is a type of constructor that initializes an object using another object of the same class. In simple terms, a constructor which creates an object by initializing it with an object of the same class, which has been created previously is known as a copy constructor. The process of initializing members of an object through a copy c
7 min read
Operator Overloading in C++
in C++, Operator overloading is a compile-time polymorphism. It is an idea of giving special meaning to an existing operator in C++ without changing its original meaning. In this article, we will further discuss about operator overloading in C++ with examples and see which operators we can or cannot overload in C++. C++ Operator OverloadingC++ has
9 min read
Templates in C++ with Examples
A template is a simple yet very powerful tool in C++. The simple idea is to pass the data type as a parameter so that we don't need to write the same code for different data types. For example, a software company may need to sort() for different data types. Rather than writing and maintaining multiple codes, we can write one sort() and pass the dat
10 min read
Friend Class and Function in C++
A friend class can access private and protected members of other classes in which it is declared as a friend. It is sometimes useful to allow a particular class to access private and protected members of other classes. For example, a LinkedList class may be allowed to access private members of Node. We can declare a friend class in C++ by using the
6 min read
Constructors in C++
Constructor in C++ is a special method that is invoked automatically at the time an object of a class is created. It is used to initialize the data members of new objects generally. The constructor in C++ has the same name as the class or structure. It constructs the values i.e. provides data for the object which is why it is known as a constructor
7 min read
Bitwise Operators in C
In C, the following 6 operators are bitwise operators (also known as bit operators as they work at the bit-level). They are used to perform bitwise operations in C. The & (bitwise AND) in C takes two numbers as operands and does AND on every bit of two numbers. The result of AND is 1 only if both bits are 1. The | (bitwise OR) in C takes two nu
7 min read
Exception Handling in C++
In C++, exceptions are runtime anomalies or abnormal conditions that a program encounters during its execution. The process of handling these exceptions is called exception handling. Using the exception handling mechanism, the control from one part of the program where the exception occurred can be transferred to another part of the code. So basica
11 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg