考虑以下代码:voidfoo(unsignedintx){}intmain(){foo(-5);return0;}此代码编译没有问题。像这样的错误会导致很多问题并且很难找到。为什么C++允许这样的转换? 最佳答案 简短的回答是因为C最初支持此类转换,并且他们不想破坏C++中的现有软件。请注意,某些编译器会对此发出警告。例如g++-Wconversion会对该构造发出警告。在许多情况下,隐式转换很有用,例如在计算中使用int时,但最终结果永远不会是负数(从算法中知道并且可以选择断言)。编辑:其他可能的解释:请记住,最初C是一种比现在C
common_type::type是unsignedlong因为关于积分提升后的操作数,标准说...[...]iftheoperandthathasunsignedintegertypehasrankgreaterthanorequaltotherankofthetypeoftheotheroperand,theoperandwithsignedintegertypeshallbeconvertedtothetypeoftheoperandwithunsignedintegertype不要称积分提升系统有问题,但似乎如果有更大的有符号整数类型可以表示有符号和无符号操作数的范围,则应该使
common_type::type是unsignedlong因为关于积分提升后的操作数,标准说...[...]iftheoperandthathasunsignedintegertypehasrankgreaterthanorequaltotherankofthetypeoftheotheroperand,theoperandwithsignedintegertypeshallbeconvertedtothetypeoftheoperandwithunsignedintegertype不要称积分提升系统有问题,但似乎如果有更大的有符号整数类型可以表示有符号和无符号操作数的范围,则应该使
在标题为Warninggeneratedduewrongstrcmpparameterhandling的问题之后,关于标准对字符类型的值表示的实际保证似乎存在一些问题。问题这看起来不错,但标准是否保证(1)将始终产生true?charunsigned*p1=...;char*p2=reinterpret_cast(p1);*p1==*p2;//(1) 最佳答案 这可能会让您大吃一惊,但在C++11标准(N3337)和即将推出的C++14(N3797)中没有这样的保证。charunsigned*p1=...;char*p2=reint
在标题为Warninggeneratedduewrongstrcmpparameterhandling的问题之后,关于标准对字符类型的值表示的实际保证似乎存在一些问题。问题这看起来不错,但标准是否保证(1)将始终产生true?charunsigned*p1=...;char*p2=reinterpret_cast(p1);*p1==*p2;//(1) 最佳答案 这可能会让您大吃一惊,但在C++11标准(N3337)和即将推出的C++14(N3797)中没有这样的保证。charunsigned*p1=...;char*p2=reint
我有一个应用程序,其中内部循环的一部分基本上是:doublesum=0;for(inti=0;i!=N;++i,++data,++x)sum+=*data*x;如果x是一个unsignedint,那么代码所用的时间是int的3倍!这是一个更大的代码库的一部分,但我把它归结为要点:#include#include#include#includetypedefunsignedcharuint8;templatedoublemoments(constuint8*data,intN,Twrap){Tpos=0;doublesum=0.;for(inti=0;i!=N;++i,++data){s
我有一个应用程序,其中内部循环的一部分基本上是:doublesum=0;for(inti=0;i!=N;++i,++data,++x)sum+=*data*x;如果x是一个unsignedint,那么代码所用的时间是int的3倍!这是一个更大的代码库的一部分,但我把它归结为要点:#include#include#include#includetypedefunsignedcharuint8;templatedoublemoments(constuint8*data,intN,Twrap){Tpos=0;doublesum=0.;for(inti=0;i!=N;++i,++data){s
我收到警告:Pe186"Pointlesscomparisonofunsignedintwithzero"当我尝试编译以下代码时:for(clLoop=cpLoopStart;clLoop>=0;clLoop--){//Dosomething}我不明白为什么。我可以理解,如果我正在寻找一个小于零的值,因为unsignedint永远不会是负数。但我在这里寻找的只是它是否等于为零,unsignedint当然可以。如果在这个循环中我尝试预先递减而不是后递减,我什至可以看到这个错误,但事实并非如此。 最佳答案 您检查unsignedint是
我收到警告:Pe186"Pointlesscomparisonofunsignedintwithzero"当我尝试编译以下代码时:for(clLoop=cpLoopStart;clLoop>=0;clLoop--){//Dosomething}我不明白为什么。我可以理解,如果我正在寻找一个小于零的值,因为unsignedint永远不会是负数。但我在这里寻找的只是它是否等于为零,unsignedint当然可以。如果在这个循环中我尝试预先递减而不是后递减,我什至可以看到这个错误,但事实并非如此。 最佳答案 您检查unsignedint是
“江南style”视频(我相信你一定听说过)在youtube上的浏览量刚刚超过20亿。事实上,谷歌表示他们从未期望视频大于32位整数......这暗示了谷歌使用int而不是unsigned的事实他们的观点柜台。我认为他们不得不重新编写代码以适应更大的View。查看他们的风格指南:https://google-styleguide.googlecode.com/svn/trunk/cppguide.html#Integer_Types...他们建议“不要使用无符号整数类型”,并给出一个很好的理由:unsigned可能是错误的。这是一个很好的理由,但可以提防。我的问题是:通常使用uns