简体   繁体   中英

Why does printf(i) give 0 as output in this program?

#include <stdio.h>

int main()
{
  int i=-1;
  !i;
  printf(i);
}

Output:

0

Why is the output zero ?

In your code,

 printf(i);

is invalid , because printf() expects a const char * as the first argument, and you're passing an int . It invokes undefined behaviour .

Turn up the compiler warnings. With the basic level of warning turned on, you should get some message along the line

warning: passing argument 1 of 'printf' makes pointer from integer without a cast

Solution: I believe, what you wanted is

printf("%d\n", i);

First how did that compile ? And even you got an output !!

printf(i); 

Format of printf- int printf(const char *format, ...);

First argument required is const char* and you pass a int . This statement in incorrect. And you would see while compiling with enabled warnings in compiler.

Correct syntax would be -

printf("%d",i);

And even if you correct your printf statement you wont get 0 as output.

!i;

This should be written as -

i=!i;

See here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM