fork download
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. #define SQUARE(x) x*x // Macro with argument
  5.  
  6. inline int square(int x) { return x*x; } // inline function
  7.  
  8. int main() {
  9. cout << SQUARE(5) << endl; // expand to 5*5 (25)
  10. int x = 2, y = 3;
  11. cout << SQUARE(x) << endl; // expand to x*x (4)
  12.  
  13. // Problem with the following macro expansions
  14. cout << SQUARE(5+5) << endl; // expand to 5+5*5+5 - wrong answer
  15. cout << square(5+5) << endl; // Okay square(10)
  16. cout << SQUARE(x+y) << endl; // expand to x+y*x+y - wrong answer
  17. cout << square(x+y) << endl; // Okay
  18. // can be fixed using #define SQUARE(x) (x)*(x)
  19.  
  20. cout << SQUARE(++x) << endl; // expand to ++x*++x (16) - x increment twice
  21. cout << x << endl; // x = 4
  22. cout << square(++y) << endl; // Okay ++y, (y*y) (16)
  23. cout << y << endl; // y = 4
  24. }
  25.  
Success #stdin #stdout 0.01s 5296KB
stdin
 
stdout
25
4
35
100
11
25
16
4
16
4