'Using #define for a function [duplicate]
After struggling with C++ typedef and define, I've tried myself some code and here it is:
#include <iostream>
#include <string>
#define sub(a,b) a-b
using namespace std;
int main()
{
    int n;
    cin >> n;
    cout <<  n*sub(5*2,3*3)+1;
}
I've find that if n=3, it'll give 22 and the equation is
3*5*2-3*3+1=22;
I can't imagine the mechanism of it, can someone help me please?
Solution 1:[1]
Just insert in this expression
n*sub(5*2,3*3)+1
the macro extension  5*2 - 3*3 and you will have
n * 5*2 - 3*3 + 1
You should rewrite the macro at least like
#define sub(a,b) ( (a ) - ( b ) )
And in C++ it is better to use inline functions (possibly with the specifier constexpr) instead pf such a macro.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source | 
|---|---|
| Solution 1 | 
