C Programming - C Preprocessor - Discussion

Discussion Forum : C Preprocessor - Find Output of Program (Q.No. 3)
3.
What will be the output of the program?
#include<stdio.h>
#define SQR(x)(x*x)

int main()
{
    int a, b=3;
    a = SQR(b+2);
    printf("%d\n", a);
    return 0;
}
25
11
Error
Garbage value
Answer: Option
Explanation:

The macro function SQR(x)(x*x) calculate the square of the given number 'x'. (Eg: 102)

Step 1: int a, b=3; Here the variable a, b are declared as an integer type and the variable b is initialized to 3.

Step 2: a = SQR(b+2); becomes,

=> a = b+2 * b+2; Here SQR(x) is replaced by macro to x*x .

=> a = 3+2 * 3+2;

=> a = 3 + 6 + 2;

=> a = 11;

Step 3: printf("%d\n", a); It prints the value of variable 'a'.

Hence the output of the program is 11

Discussion:
21 comments Page 1 of 3.

Mangesh Kulkarni said:   4 years ago
The Rule of macros is Find and Replace.
(3)

Kunijiuma said:   5 years ago
#include<stdio.h>
int SQR(int x){return x*x;}
int main()
{
int a, b=3;
a = SQR(b+2);
printf("%d\n", a);
return 0;
}

o/p:
25.

And the result should be 25 instead of 11.
(1)

Jyothi said:   10 years ago
1) Division.

2) Multiplication.

3) Add so definitely answer will 11.

Akshay said:   8 years ago
If sqr(x) (x)*(x) then it should be 25.
And if sqr(x) (x*x) then it will be 11.

Ravi said:   8 years ago
If sqr(x) x*x then it should be 11.

Manoj said:   8 years ago
#define SQR(x)(x*x)
#include<stdio.h>
int main()
{
int a, b=3;
a = SQR(b+a);
printf("%d\n", a);
return 0;
}

The output will be a=3, how is possible? Pease explain me.

Nithish said:   9 years ago
If we give (b + 2) then we get 25.

Nithish said:   9 years ago
If we convert it in postfix expression, then evaluate it will be 11.

Alli mohammed said:   9 years ago
Write a program to calculate the valude of x, Where x=(3+4ab)3/2c^2.

Can anyone help me with this?

Thippesh_madakari said:   9 years ago
At the compilation stage, only 3 is passed into the macro.

Because we are passing b+2, which will be calculated at the run time. During run time it will become 9+2=11.


Post your comments here:

Your comments will be displayed after verification.