32. Square with Macro and Inline Function

#include <iostream>
using namespace std;

#define SQUARE(x) (x*x)

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

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

    int a = n;
    int b = n;

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

    return 0;
}

Solution Details

  • SQUARE(++a) expands to (++a * ++a) → a is incremented twice.
  • square(++b) increments b once, then calculates safely.
     

👉 Layman’s explanation:

  • Macro is like pasting the formula (++a * ++a) directly → a gets bumped twice.
  • Inline function is like a calculator: it first takes the incremented number, then squares it.
     

Significance for Embedded Developers

  • Using macros in embedded code for sensor values, register fields, or calculations can cause subtle bugs when the same variable is evaluated more than once.
     
  • Inline functions solve this problem with the same efficiency.

     
Loading...

Input

5

Expected Output

Macro Square: 49 Inline Square: 36