为什么C ++允许从int到unsigned int的隐式转换? [英] Why does C++ allows implicit conversion from int to unsigned int?

查看:186
本文介绍了为什么C ++允许从int到unsigned int的隐式转换?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下代码:

void foo(unsigned int x)
{

}

int main()
{
  foo(-5);
  return 0;
}

编译没有问题。这样的错误可能会导致很多问题,很难找到。为什么C ++允许这样的转换?

Compiles with no problems. Errors like this can cause lots of problems and are hard to find. Why C++ allows such conversion?

推荐答案

简单的答案是因为C最初支持这种转换, C ++中的软件。

The short answer is because C supported such conversions originally and they didn't want to break existing software in C++.

请注意,一些编译器会在此警告。例如 g ++ -Wconversion 会对该结构发出警告。

Note that some compilers will warn on this. For example g++ -Wconversion will warn on that construct.

在许多情况下,隐式转换是有用的,例如当在计算中使用 int 时,但是最终结果将永远不为负(从算法知道并且可选地被断言)。

In many cases the implicit conversion is useful, for example when int was used in calculations, but the end result will never be negative (known from the algorithm and optionally asserted upon).

编辑:附加可能的解释:记住,原来C是一个比C ++更宽松的语言。使用K& R风格函数声明,编译器不会检测到这种隐式转换,因此为什么要在语言中限制它。例如你的代码看起来大概是这样:

Additional probable explanation: Remember that originally C was a much looser-typed language than C++ is now. With K&R style function declarations there would have been no way for the compiler to detect such implicit conversions, so why bother restricting it in the language. For example your code would look roughly like this:

int foo(x)
unsigned int x
{

}

int main()
{
  foo(-5);
  return 0;
}

而声明本身就是 int foo x);

编译器实际上依靠程序员将正确的类型传递到每个函数调用中,调用网站。然后当函数实际被调用时,堆栈(etc)上的数据被解释为函数声明指示的方式。

The compiler actually relied on the programmer to pass the right types into each function call and did no conversions at the call site. Then when the function actually got called the data on the stack (etc) was interpreted in the way the function declaration indicated.

一旦代码写成依赖于那种隐式转换,即使将函数原型与实际类型信息一起添加,它也将变得更难从ANSI C中删除。这可能是为什么它现在仍然在C。然后C ++来了,再次决定不破坏与C的向后兼容性,继续允许这样的隐式转换。

Once code was written that relied on that sort of implicit conversion it would have become much harder to remove it from ANSI C even when function prototypes were added with actual type information. This is likely why it remains in C even now. Then C++ came along and again decided to not break backwards compatibility with C, continuing to allow such implicit conversions.

这篇关于为什么C ++允许从int到unsigned int的隐式转换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆