C++ Macros

⚡ C++ Macros – Shortcuts for Your Code

Want a quick way to reuse code without writing functions? Say hello to macros – your coding shortcuts! 🚀

In C++, a macro is a piece of code that gets replaced by something else before the program even compiles. It’s like a find and replace feature for your code.

🛠️ Syntax

#define NAME replacement

You define it once, and the compiler swaps every use of NAME with replacement.

🔧 Example: Simple Macro

#include <iostream>
#define PI 3.14159

int main() {
    float r = 5;
    float area = PI * r * r;
    std::cout << "Area of circle: " << area << std::endl;
    return 0;
}
  

Try It Now

🔧 Example: Macro with Parameters

Macros can act like mini-functions too:

#include <iostream>
#define SQUARE(x) ((x)*(x))

int main() {
    std::cout << "Square of 6: " << SQUARE(6) << std::endl;
    return 0;
}
  

Try It Now

⚠️ Be Careful!

  • Macros don’t follow normal C++ rules—they’re replaced before compilation.
  • They don’t do type checking or scoping.
  • Use parentheses to avoid weird behavior: #define SQUARE(x) ((x)*(x))

🧠 Simple Way to Remember

One word, many meanings: Macros are nicknames for code. Define once, use everywhere!