By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
455,434 Members | 1,858 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 455,434 IT Pros & Developers. It's quick & easy.

float and integers

P: n/a
consider following code snippet..
________________________
float a=3.0;
int b=1,c=2;
printf("%d %d %d ",a,b,c);
_________________________

above code give output
0 0 0
i can understand first zero as wrong format(%d) given for a,but i
could not get that why b and c are also printing as zero....


Nov 15 '08 #1
Share this Question
Share on Google+
2 Replies


P: n/a
On Nov 15, 2:54 pm, "c.lang.mys...@gmail.com"
<c.lang.mys...@gmail.comwrote:
consider following code snippet..
________________________
float a=3.0;
int b=1,c=2;
printf("%d %d %d ",a,b,c);
a is float. %d expects int. You invoked UB, you can't expect anything
from your program.
_________________________

above code give output
0 0 0
i can understand first zero as wrong format(%d) given for a,but i
could not get that why b and c are also printing as zero....
Nov 15 '08 #2

P: n/a
"c.***********@gmail.com" <c.***********@gmail.comwrites:
consider following code snippet..
________________________
float a=3.0;
int b=1,c=2;
printf("%d %d %d ",a,b,c);
_________________________

above code give output
0 0 0
i can understand first zero as wrong format(%d) given for a,but i
could not get that why b and c are also printing as zero....
Once you invoke undefined behavior, all bets are off. By attempting
to print a float object with a "%d" format, you lied to the system;
it's under no obligation to do anything else you ask of it.

Here's one plausible scenario for the behavior you're seeing:

An argument of type float is promoted to double. It's likely that int
is 32 bits and double is 64 bits on your system. So you're passing a
64-bit quantity to printf, and printf is then attempting to grab
argument values of size 32, 32, and 32.

That's only one possibility for what's going on when you run your
program. But really, analyzing just what's happening is most likely a
waste of time. You code has an error; the answer is to fix it.

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
Nokia
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
Nov 15 '08 #3

This discussion thread is closed

Replies have been disabled for this discussion.