1

Why is my simple C program printing "hello world" and being compiled with no errors and is running fine when I gave a floating point number next to return statement? Shouldn't it be an error to do so?

Here is my code:

#include<stdio.h>
int main()
{
    printf("hello world");
    return 2.1;
}
moooeeeep
  • 28,315
  • 14
  • 88
  • 166
surya dutt
  • 13
  • 2
  • why it should give error, it will give only warning – venki Aug 27 '15 at 11:19
  • implicitly it will convert float to int – venki Aug 27 '15 at 11:19
  • [What should main() return in C and C++?](http://stackoverflow.com/q/204476/995714) – phuclv Aug 27 '15 at 11:22
  • possible duplicate of [Does the return process cast/convert the type required to a result according to the C standard, or is that only supported in certain implementations?](http://stackoverflow.com/questions/3457497/does-the-return-process-cast-convert-the-type-required-to-a-result-according-to) – moooeeeep Aug 27 '15 at 11:42

5 Answers5

3

When you return a different type from the declared type of the function, the value is automatically converted to the declared type. So it's equivalent to doing:

return (int) 2.1;
Barmar
  • 596,455
  • 48
  • 393
  • 495
  • I also want to ask that "why main function in c language returns only integer but not float pointing number or a string" – surya dutt Aug 27 '15 at 11:21
  • @suryadutt because it's the error code returned to the OS, which is not a float – phuclv Aug 27 '15 at 11:22
  • @venki The answer you link refers to C++ (which differs slightly from C in this respect). – moooeeeep Aug 27 '15 at 11:45
  • @suryadutt: The language definition mandates that `main` return an `int`. Note that the return value of `main` is usually a status code for the runtime environment, so it makes sense for it to be an integer type. Per section 5.1.2.2.1 of the [C language standard](http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf), an implementation *may* provide an alternate signature for `main`, which it *must* document (although the ones I've seen usually change the number of arguments to `main`, not its return type). – John Bode Aug 27 '15 at 15:47
3

For the same reason of

int main(void)
{
    // ...
    int x = 2.1;

    // ...
   return x;
}

This is called implicit conversion.

edmz
  • 7,675
  • 2
  • 21
  • 43
1

The return code will be casted automatically on return. The long version is

return (int) 2.1;
Piters
  • 394
  • 2
  • 9
0

Your code will return an integer because the compiler will take care of casting the float into an integer.

Johann Horvat
  • 1,175
  • 1
  • 12
  • 18
0

This is normal as the value well be implicitly converted to your declared type. the compiler will not mind but you'll get unexpected results at the runtime in general and in this specific case the casting to (int).

eddawy
  • 11
  • 2