Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does the preprocessor work in C?

Tags:

c

Why is the answer for the below code 16? Can anybody explain the working of this program?

#define SQUARE(n) n*n
void main()
{
    int j;      
    j =16/SQUARE(2);

    printf("\n j=%d",j);
    getch();
}

If we write the same code like below, then the answer is 4:

//the ans is 4 why?
#include<stdio.h>
#include<conio.h>

#define SQUARE(n) n*n

void main()
{
    int j;      
    j =16/(SQUARE(2));

    printf("\n j=%d",j);
    getch();
}
like image 910
Arvind Lairenjam Avatar asked Jan 30 '13 13:01

Arvind Lairenjam


People also ask

How does the preprocessor work?

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 preprocessor with example in C?

Examples of some preprocessor directives are: #include, #define, #ifndef etc. Remember that the # symbol only provides a path to the preprocessor, and a command such as include is processed by the preprocessor program. For example, #include will include extra code in your program.

Why do we need preprocessor in C?

Preprocessor directives, such as #define and #ifdef , are typically used to make source programs easy to change and easy to compile in different execution environments. Directives in the source file tell the preprocessor to take specific actions.

What is a preprocessor directive and how does it work?

What Does Preprocessor Directive Mean? Preprocessor directives are lines included in a program that begin with the character #, which make them different from a typical source code text. They are invoked by the compiler to process some programs before compilation.


2 Answers

The preprocessor just replaces the text, exactly as written.

So, the macro call SQUARE(2) becomes literally 2*2.

In your case, that means the whole expression becomes 16/2*2, which because of C's precedence rules evaluates to (16/2)*2, i.e. 16.

Macros should always be enclosed in parenthesis, and have each argument enclosed as well.

If we do that, we get:

#define SQUARE(n)  ((n) * (n))

which replaces to 16/((2) * (2)), which evaluates as 16/4, i.e. 4.

The parens around each argument makes things like SQUARE(1+1) work as expected, without them a call such as 16/SQUARE(1+1) would become 16/(1+1*1+1) which is 16/3, i.e. not at all what you'd want.

like image 181
unwind Avatar answered Oct 17 '22 02:10

unwind


Order of operations. Your expression is evaluating to:

 j = 16 / 2 * 2

which equals 16. Make it:

#define SQUARE(n) (n*n) 

which will force the square to be evaluated first.

like image 40
CJ_912 Avatar answered Oct 17 '22 03:10

CJ_912