Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does this program work?

#include <stdio.h>  int main() {     float a = 1234.5f;     printf("%d\n", a);     return 0; } 

It displays a 0!! How is that possible? What is the reasoning?


I have deliberately put a %d in the printf statement to study the behaviour of printf.

like image 324
Lazer Avatar asked Mar 04 '10 08:03

Lazer


People also ask

What is a computer program and how does it work?

A computer program is a sequence or set of instructions in a programming language for a computer to execute. Computer programs are one component of software, which also includes documentation and other intangible components.

Which program makes the computer work?

System software controls a computer's internal functioning, chiefly through an operating system, and also controls such peripherals as monitors, printers, and storage devices.

What is the purpose of a program?

The purpose of a program provides the framework that sets the direction of the program, while the goals and objectives provide a plan as to how the purpose will be achieved.


1 Answers

That's because %d expects an int but you've provided a float.

Use %e/%f/%g to print the float.


On why 0 is printed: The floating point number is converted to double before sending to printf. The number 1234.5 in double representation in little endian is

00 00 00 00  00 4A 93 40 

A %d consumes a 32-bit integer, so a zero is printed. (As a test, you could printf("%d, %d\n", 1234.5f); You could get on output 0, 1083394560.)


As for why the float is converted to double, as the prototype of printf is int printf(const char*, ...), from 6.5.2.2/7,

The ellipsis notation in a function prototype declarator causes argument type conversion to stop after the last declared parameter. The default argument promotions are performed on trailing arguments.

and from 6.5.2.2/6,

If the expression that denotes the called function has a type that does not include a prototype, the integer promotions are performed on each argument, and arguments that have type float are promoted to double. These are called the default argument promotions.

(Thanks Alok for finding this out.)

like image 155
kennytm Avatar answered Sep 24 '22 22:09

kennytm