float and integers

C

c.lang.myself

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....
 
V

vippstar

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.
 
K

Keith Thompson

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,007
Latest member
obedient dusk

Latest Threads

Top