31. Square of a Number

#include <iostream>
using namespace std;

#define SQUARE(x) (x*x)

inline int square(int x) {
    return x * x;
}

int main() {
    int n;
    cin >> n;

    cout << "Macro Square: " << SQUARE(n) << "\n";
    cout << "Inline Square: " << square(n) << "\n";

    return 0;
}

Solution Details

  • The macro SQUARE(x) is replaced by the preprocessor directly as text.
  • The inline function square() is a real function, but the compiler can optimize it by expanding it inline.
  • For simple cases (like 5 or -3), both behave the same.
     

👉 Layman’s explanation:

  • A macro is like writing down the formula (x*x) on a sticky note and pasting it into your code whenever needed.
  • An inline function is like having a proper reusable calculator button called “square” — safer and more reliable.
     

Significance for Embedded Developers

  • In older C firmware, macros were often used for speed.
  • Modern C++ prefers inline functions because:
    • They are type-safe.
    • They don’t cause unexpected side effects.
    • They compile just as efficiently as macros.

 

  • This helps embedded developers write fast and safe code.

     
Loading...

Input

5

Expected Output

Macro Square: 25 Inline Square: 25