18. 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;
}

Explanation & Logic Summary:

  • The macro SQUARE(x) is expanded by the preprocessor as text
  • Proper parentheses ensure correct behavior for all expressions
  • The inline function is type-safe and avoids macro side effects
  • Both return the same result for valid inputs

Layman’s explanation:

  • A macro pastes code directly — so it must be written very carefully
  • An inline function behaves like a real function, just faster
  • Inline functions are safer and preferred in modern embedded C++

Firmware Relevance & Real-World Context:

  • Macros were historically used in embedded firmware for performance
  • Unsafe macros can cause subtle bugs in low-level systems
  • Inline functions provide safety, clarity, and equivalent performance
  • This exercise reinforces safe macro design, a critical embedded skill

 

 

 

 

Loading...

Input

5

Expected Output

Macro Square: 25 Inline Square: 25