3

Consider this simple code:

int foo = 4;
double d1 = sin (foo);
double d2 = foo * 0.1;

When i compile this with gcc, the results are as expected (i.e. mathematically correct), even though sin() expects a double as its argument. It appears gcc has implicitly casted foo to double.

How portable is this kind of implicit casting, what are the limitations, where can I find documentation?

Side note: I do know C++ compilers are required to handle such casting correctly.

Rob
  • 5,223
  • 5
  • 41
  • 62
idefixs
  • 712
  • 1
  • 4
  • 14

3 Answers3

5

The C99 standard allows this kind of implicit conversion (see section 6.5.2.2, paragraph 7).

Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680
4

It is completely portable. This kind of casting is specified in the C language standard that all compilers must obey.

Tudor
  • 61,523
  • 12
  • 102
  • 142
0

As long as you supply the correct prototype (by including the proper header, #include <math.h>) the behaviour when calling sin (converting the argument to double) is mandated by the Standard.

Without the prototype in scope, it is Undefined Behaviour to supply an argument which, after default promotion, has a type different than the function expects.

pmg
  • 106,608
  • 13
  • 126
  • 198
  • 1
    It's worse than that, isn't it? If the prototype isn't in scope, then default promotions will be applied to all arguments before being placed on the stack, regardless of whether they're of differing types to the underlying function definition. – Oliver Charlesworth Nov 07 '11 at 14:53