I saw this below code in an website.
I could not able to understsnd how the result is coming as 11
, instead of 25
or 13
.
Why I am thinking 25
because SQ(5) 5*5
or 13
because
SQ(2) = 4;
SQ(3) = 9;
may be final result will be 13 (9 + 4)
But surprised to see result as 11
.
How the result is coming as 11
?
using namespace std;
#define SQ(a) (a*a)
int main()
{
int ans = SQ(2 + 3);
cout << ans << endl;
system("pause");
}
Macro expansion is an integral part of eval and compile . Users can also expand macros at the REPL prompt via the expand REPL command; See Compile Commands. Macros can also be expanded programmatically, via macroexpand , but the details get a bit hairy for two reasons.
Overview. Macro in C programming is known as the piece of code defined with the help of the #define directive. Macros in C are very useful at multiple places to replace the piece of code with a single value of the macro. Macros have multiple types and there are some predefined macros as well.
Macros are expanded by the preprocessor, which is a separate program that runs before the compiler proper. Macros perform a simple text substitution.
This macro expands to the name of the current input file, in the form of a C string constant. The precise name returned is the one that was specified in `#include' or as the input file name argument. This macro expands to the current input line number, in the form of a decimal integer constant.
The preprocessor does a simple text substitution on the source code. It knows nothing about the underlying language or its rules.
In your example, SQ(2 + 3)
expands to (2 + 3*2 + 3)
, which evaluates to 11
.
A more robust way to define SQ
is:
#define SQ(a) ((a)*(a))
Now, SQ(2 + 3)
would expand to ((2 + 3)*(2 + 3))
, giving 25
.
Even though this definition is an improvement, it is still not bullet-proof. If SQ()
were applied to an expression with side effects, this could have undesired consequences. For example:
f()
is a function that prints something to the console and returns an int
, SQ(f())
would result in the output being printed twice.i
is an int
variable, SQ(i++)
results in undefined behaviour.For further examples of difficulties with macros, see Macro Pitfalls.
For these reasons it is generally preferable to use functions rather than macros.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With