I'm learning C, but I do not understand this:
#define square(x) x*x
a = square(2+3) //a = 11
When this is run, why does a
end up being 11
?
The C preprocessor is a macro processor that is used automatically by the C compiler to transform your program before actual compilation. It is called a macro processor because it allows you to define macros, which are brief abbreviations for longer constructs.
In computer science, a preprocessor (or precompiler) is a program that processes its input data to produce output that is used as input to another program. The output is said to be a preprocessed form of the input data, which is often used by some subsequent programs like compilers.
The C preprocessor is the macro preprocessor for the C, Objective-C and C++ computer programming languages. The preprocessor provides the ability for the inclusion of header files, macro expansions, conditional compilation, and line control.
The C preprocessor modifies a source file before handing it over to the compiler, allowing conditional compilation with #ifdef, defining constants with #define, including header files with #include, and using builtin macros such as __FILE__.
It expands to 2+3*2+3
, which is equivalent to 2+(3*2)+3
. Use parentheses to fix it:
#define square(x) ((x)*(x))
Now try it with square(x++)
and you'll run into more problems (undefined behavior). Avoid doing this as a macro if you can.
square(2+3)
expands to 2+3*2+3
which is equivalent to 2+(3*2)+3
[*
has higher precedence than +
]
On gcc you can use -E
option to see what your preprocessor generates
C:\Users\SUPER USER>type a.c
#define square(x) x*x
int main()
{
a = square(2+3); //a = 11
}
C:\Users\SUPER USER>gcc -E a.c
# 1 "a.c"
# 1 "<built-in>"
# 1 "<command-line>"
# 1 "a.c"
int main()
{
a = 2+3*2+3;
}
Remedy
Try this
#define square(x) ((x)*(x))
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