Go4Expert

Go4Expert (http://www.go4expert.com/)
-   C (http://www.go4expert.com/forums/c/)
-   -   confusion with format string (http://www.go4expert.com/forums/confusion-format-string-t8431/)

shyam_oec 24Jan2008 00:12

confusion with format string
 
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?) :confused:

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

Salem 24Jan2008 00:46

Re: confusion with format string
 
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)


shabbir 24Jan2008 07:48

Re: confusion with format string
 
%d and %f are for integer and float respectively.

shyam_oec 24Jan2008 11:56

Re: confusion with format string
 
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....

Salem 24Jan2008 13:49

Re: confusion with format string
 
> 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.

asadullah.ansari 24Jan2008 14:20

Re: confusion with format string
 
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.


All times are GMT +5.5. The time now is 01:14.