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:
    1. Save time and effort by reusing code
    2. Simplify complex code
    3. Increase code readability
    4. 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
    1. Repeating a sequence of commands
    2. Performing calculations or data manipulation
    3. Generating code based on input parameters
    4. 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:

  1. #define print(x) cout << x << endl; defines a macro named print that takes a single parameter x.
  2. The macro expands to cout << x << endl, which is the standard output statement in C++.
  3. In the main function, the first output statement uses the standard cout statement to print “hello from gurucodes.”.
  4. The second output statement uses the print macro to print “Welcome to programming and the DSA course.”.
  5. 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:
    1. Validating user input
    2. Checking if a value is within a certain range
    3. 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

Questions? : Reach Out