Natan Yellin
Natan Yellin

Reputation: 6387

Is printf("%d", 1.0) undefined?

According to section 4.9.6.1 of the C89 draft, %d is a character that specifies the type of conversion to be applied.

The word conversion implies, in my opinion, that printf("%d", 1.0) is defined.

Please confirm or refute this.

Upvotes: 1

Views: 336

Answers (4)

Johannes Schaub - litb
Johannes Schaub - litb

Reputation: 507035

The conversion is the conversion of a language value to a lexical representation of that value.

Your theory is wrong; behavior is undefined. The spec says (7.19.6.1p8 and 9, using C99 TC2):

The int argument is converted to signed decimal in the style [−]dddd.

And

If any argument is not the correct type for the corresponding conversion specification, the behavior is undefined.

Upvotes: 12

R.. GitHub STOP HELPING ICE
R.. GitHub STOP HELPING ICE

Reputation: 215287

The word "conversion" here is referring to the conversion of an int (which is the only acceptable argument type here) to a string of characters that make of the decimal representation of that int. It has nothing to do with conversion from other types (such as double) to int.

Upvotes: 2

bmargulies
bmargulies

Reputation: 100051

Printf is a varargs function, so no conversion is possible. The compiler just arranges to push a double onto the arguments list. Printf has no way to find out that it's a double versus an int versus an elephant. Result? Chaos.

Upvotes: 8

Martin Beckett
Martin Beckett

Reputation: 96109

Not sure if it's officially undefined or an error - but it's wrong!

Upvotes: 0

Related Questions