in Programming edited by
425 views
3 votes
3 votes

Read this code snippet :

void main()
{
int i;
char a[]="\0";
if(printf("%s\n",a))
printf(" GATE 2018\n");
else
printf("Forget GATE\n");
}

The output is :

  1. Compiler Error
  2. Forget GATE
  3. GATE $2018$
  4. Runtime error
in Programming edited by
by
425 views

3 Answers

5 votes
5 votes
Best answer
Printf returns number of characters printed.
Printing NULL will return 0.
But there is a new line after NULL.   (\n)
Because of that new line, 1 will be returned by printf.
So output is C.
selected by
by
2 votes
2 votes
Explanation:
Printf will return how many characters does it print.

Hence printing a new line character "\n" returns 1 which makes the if statement true, thus "GATE 2018" is printed.
edited by

4 Comments

ok, tnks :)
1
1
@Bikram sir,  printing NULL returns 0, because of that new line,  \n     1 is returned.  You can test by removing new line.
3
3

yes, due to '\n' the condition part of if() becomes true .

here i remove '\n' , now it becomes https://ideone.com/y6aibK 

gives out put 

Forget GATE
2
2
0 votes
0 votes
void main()
{
int i;
char a[]="\0";
if(printf("%s\n",a))
printf(" GATE 2018\n");
else
printf("Forget GATE\n");
}

Because of \n inside printf condition will become true (\n is newline character so it will print nothing but will insert a new line) and output will be GATE 2018.

void main()
{
int i;
char a[]="\0";
if(printf("%s",a))
printf(" GATE 2018\n");
else
printf("Forget GATE\n");
}

Now output will be : Forget GATE

Some ref : https://stackoverflow.com/questions/18654465/how-0-is-treated-in-printf#:~:text=So%20empty%20is%20printed%20as%20output.&text=The%20main%20concept%20here%20is,in%20the%20statement%20if%20any%20

Answer:

Related questions