C Programming - C Preprocessor - Discussion

Discussion Forum : C Preprocessor - Find Output of Program (Q.No. 9)
9.
What will be the output of the program?
#include<stdio.h>
#define FUN(arg) do\
                 {\
                    if(arg)\
                        printf("IndiaBIX...", "\n");\
                  }while(--i)

int main()
{
    int i=2;
    FUN(i<3);
    return 0;
}
IndiaBIX...
IndiaBIX...
IndiaBIX
IndiaBIX... IndiaBIX...
Error: cannot use control instructions in macro
No output
Answer: Option
Explanation:

The macro FUN(arg) prints the statement "IndiaBIX..." untill the while condition is satisfied.

Step 1: int i=2; The variable i is declared as an integer type and initialized to 2.

Step 2: FUN(i<3); becomes,

do
{
    if(2 < 3)
    printf("IndiaBIX...", "\n");
}while(--2)

After the 2 while loops the value of i becomes '0'(zero). Hence the while loop breaks.

Hence the output of the program is "IndiaBIX... IndiaBIX..."

Discussion:
22 comments Page 2 of 3.

Nejat sultan said:   10 years ago
2<3....2.

1<3....1.

This time while (0). It fails here. So functions 2 times.

Ishaan said:   10 years ago
I agree with @Vince it seems an infinite loop.

Vince Bala said:   10 years ago
I don't get it.

When i becomes 0, the condition is still true (0<3).

So it will call the print function 3 times.

Sathiesha reddy said:   1 decade ago
The macro FUN(arg) prints the statement "IndiaBIX..." until the while condition is satisfied.

FUN(i<3); becomes true=1, hence condition satisfies thus calls the fun given in the code. Thus runs the below function twice.

do
{
if(2 < 3)
printf("IndiaBIX...", "\n");
}while(--2)

After the 2 while loops the value of i becomes '0'(zero). Hence the while loop breaks.

Hence the output of the program is "IndiaBIX... IndiaBIX..."

Charan said:   1 decade ago
Actually the answer will be only IndiaBIX.
Because let us consider FUN(2<3).

Which means true = 1.
i.e FUN(1).

Taniya said:   1 decade ago
@Sayli.

Because comma operator returns the rightmost value in such case.

Sayli said:   1 decade ago
Why 1, 2, 3, 4 are discarded?

Chaitu said:   1 decade ago
Actually I have seen this some where in some other question saying..comma operator used here in printf() doesn't act as operator..similarly in scanf()..for()..the comma used here is different than..the above one(comma operator)..in this case we can see the effect of comma operator..
//effect of comma operator

main()
{
int i=5;
int j=i+(1,2,3,4,5);//1,2,3,4 r discarded & 5 is considered
printf("%d",j);
getch();
}

o/p: 10.

Mayur said:   1 decade ago
But we has used, operator ;by rule of comma first is evaluate then discard it, so only "\n" is executed?

ARupinderjit said:   1 decade ago
Yar if you do printf("India","Bix"); then it'll print only first quoted string,that is,India.so is the answer.


Post your comments here:

Your comments will be displayed after verification.