Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Macro expansion in context of arithmetic expression?

Tags:

c++

c

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");
}
like image 515
Rasmi Ranjan Nayak Avatar asked Dec 05 '12 07:12

Rasmi Ranjan Nayak


People also ask

What is macro expansion?

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.

What is a macro expression in C?

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.

How macro expansion is done?

Macros are expanded by the preprocessor, which is a separate program that runs before the compiler proper. Macros perform a simple text substitution.

How does macro expansion work in C?

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.


1 Answers

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:

  • If f() is a function that prints something to the console and returns an int, SQ(f()) would result in the output being printed twice.
  • If 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.

like image 51
NPE Avatar answered Oct 21 '22 00:10

NPE