简体   繁体   English

当返回值的类型与声明的返回类型不同时,返回值会怎样?

[英]What happens to return value when its type differs from the declared return type?

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? 为什么我的简单C程序打印“ hello world”并且没有错误地进行编译并且在return语句旁边给出浮点数时运行正常? Shouldn't it be an error to do so? 这样做不是错误吗?

Here is my code: 这是我的代码:

#include<stdio.h>
int main()
{
    printf("hello world");
    return 2.1;
}

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;

For the same reason of 出于同样的原因

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

    // ...
   return x;
}

This is called implicit conversion . 这称为隐式转换

The return code will be casted automatically on return. 返回代码将在返回时自动转换。 The long version is 长版是

return (int) 2.1;

您的代码将返回一个整数,因为编译器将负责将float转换为整数。

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). 编译器不会介意,但通常会在运行时得到意外结果,在这种情况下,强制转换为(int)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 当我们将返回类型为void的函数调用返回值分配给int变量时会发生什么? - What happens when we assign a function call return value with return type void to a int variable? 将函数的返回类型存储在其他类型的变量中时会发生什么? - What happens when storing a function's return type in a variable of a different type? 当用作返回值时,临时堆栈分配的指针会发生什么? - What happens to a temporary stack allocated pointer when used as a return value? 类型强制转换C中pthread的返回值时出现意外结果 - unexpected result when type casting the return value from pthread in C 什么是typeof的返回类型? - what is the return type of typeof? 枚举|的返回类型是什么? - What is the return type of enum |? 当您键入将整数值转换为char指针时会发生什么? - What happens when you type cast an integer value into a char pointer? 如果main()没有返回int值会发生什么? - What happens if main() does not return an int value? 使用 C 程序执行代码时,支持从 db2/大型机返回值的可能数据类型是什么 - what would be possible data type to support return value from db2/mainframe when executing code using C program 当类型已知时,如何从void指针返回具有类型的指针 - How to return a pointer with a type from a void pointer, when the type is known
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM