Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C preprocessors and order of operations

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?

like image 933
jhon Avatar asked Apr 27 '11 16:04

jhon


People also ask

Which are C preprocessors?

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.

What is preprocessor in operating system?

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.

What is C preprocessor and how it works?

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.

Does C have preprocessor directives?

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__.


2 Answers

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.

like image 80
Fred Larson Avatar answered Oct 06 '22 00:10

Fred Larson


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))
like image 33
Prasoon Saurav Avatar answered Oct 05 '22 23:10

Prasoon Saurav