Macros and Type range Macros
Macros
- A macro is a set of instructions or a code snippet that can be expanded or replaced with a longer piece of code.
- Macros are often used in programming to:
- Save time and effort by reusing code
- Simplify complex code
- Increase code readability
- Reduce errors
- Macros can be thought of as shortcuts or abbreviations for longer code segments.
- They are typically defined once and can be used multiple times throughout a program.
- Macros can perform various tasks, such as
- Repeating a sequence of commands
- Performing calculations or data manipulation
- Generating code based on input parameters
- Implementing conditional logic or loops
- Macros can greatly improve coding efficiency and readability, but they should be used judiciously to avoid code obfuscation and maintainability issues.
Syntax
- #define name code
Example:
#include <iostream>
using namespace std;
#define print(x) cout << x << endl;
int main()
{
cout << "hello from gurucodes" << endl;
print("Welcome to programming and DSA course")
return 0;
}
The output of this program will be:
hello from gurucodes
Welcome to programming and DSA course
Here’s a breakdown:
- #define print(x) cout << x << endl; defines a macro named print that takes a single parameter x.
- The macro expands to cout << x << endl, which is the standard output statement in C++.
- In the main function, the first output statement uses the standard cout statement to print “hello from gurucodes.”.
- The second output statement uses the print macro to print “Welcome to programming and the DSA course.”.
- The macro replaces x with the string argument, resulting in cout << “Welcome to programming and DSA course” << endl;.
Type Range Macros
- Type range macros are a type of macro that allows you to check if a value falls within a specific range.
- They are often used to validate input values or to ensure that a value is within a certain range.
- Macros can be useful in a variety of situations, such as:
- Validating user input
- Checking if a value is within a certain range
- Ensuring that a value is within a specific bounds
- Type range macros in C++ are predefined constants that specify the limits of fundamental data types.
#include<iostream>
#include<limits.h>
#include<float.h>
using namespace std;
int main()
{
cout<< LLONG_MAX <<endl;
cout<< INT_MIN <<endl;
cout<< CHAR_MIN <<endl;
cout<< CHAR_MAX <<endl;
cout<< FLT_MIN <<endl;
return 0;
}
The output of this program will be:
9223372036854775807
-2147483648
0
255
1.17549435e-38