confusion with format string

shyam_oec's Avatar, Join Date: Nov 2007
Contributor
main()
{
float x=1.0;
int y=3;
printf("x=%d",x);
printf("\ny=%f",y);
}

output:
x=0
y=285737.000011(why this unexpected output?)

though x is floating type variable,when it is displayed in int farmat why it's output is x=0
on the other hand value of y is something annoying
0
Salem's Avatar, Join Date: Nov 2007
Ambitious contributor
You used the wrong format for the printf commands.
Code:
$ gcc -W -Wall -ansi -pedantic -O2 foo.c
foo.c: In function `main':
foo.c:14: warning: int format, double arg (arg 2)
foo.c:15: warning: double format, different type arg (arg 2)
0
shabbir's Avatar, Join Date: Jul 2004
Go4Expert Founder
%d and %f are for integer and float respectively.
0
shyam_oec's Avatar, Join Date: Nov 2007
Contributor
Quote:
Originally Posted by shabbir
%d and %f are for integer and float respectively.
it's fine that %d and %f are for integer and float,but can u tell why we get such an output....
0
Salem's Avatar, Join Date: Nov 2007
Ambitious contributor
> but can u tell why we get such an output.
Because your code is broken.

Broken code produces whatever it feels like, regardless of what you might expect / like / desire / hope for.

Use a compiler which can check your printf / scanf format strings (like I posted), and don't run any code which has warnings in it.
0
asadullah.ansari's Avatar, Join Date: Jan 2008
TechCake
When you will go definition of printf. A sample of it..
Code:
int printf( . . . )
{
     //Some code
   ...........
   ...............
  //va_arg : taking conversion symbol(%d, %f etc) and associated with values
 switch( TYPE)
 { 

  //Case INT_TYPE : Some code for Integer
  // Case FLOAT_TYPE : some code for Float 
  // Case CHAR_TYPE  : some code for char
    ......
   .....
  }
return ;
}
when conversion sybol(%d) and value is double then it's value will be junk. because printf function does not check for type casting. Just %d and its associated values. If it's matching then it will go correct switch case and correct value. Else wrong switch case will execute and value will be junk.