保健励志美文体育育儿作文
投稿投诉
作文动态
热点娱乐
育儿情感
教程科技
体育养生
教案探索
美文旅游
财经日志
励志范文
论文时尚
保健游戏
护肤业界

C类型转换规则何时发生隐式类型转换及强制类型转换适用场合

  C做为强类型语言,要求编译期的类型声明与检查,要求表达式中各操作数的类型(包括赋值操作的左值和右值,以及形参和实参)具有一致性,但同时也允许一定的灵活性,允许类型在一定程度上的兼容,也就是允许类型遵循一定规则下的隐式转换和强制转换。
  Thetypeoftheoperand(s)determinewhetheranexpressionislegaland,iftheexpressionislegal,determinesthemeaningoftheexpression。However,inCsometypesarerelatedtooneanother。Whentwotypesarerelated,wecanuseanobjectorvalueofonetypewhereanoperandoftherelatedtypeisexpected。Twotypesarerelatedifthereisaconversionbetweenthem。
  表达式是否合法取决于操作数的类型,而且合法的表达式其含义也由其操作数类型决定。但是,在C中,某些类型之间存在相关的依赖关系。若两种类型相关,则可在需要某种类型的操作数位置上,使用该类型的相关类型对象或值。如果两个类型之间可以相互转换,则称这两个类型相关。1类型转换规则
  1。1TheArithmeticConversions算术转换
  Thelanguagedefinesasetofconversionsamongthebuiltintypes。Amongthese,themostcommonarethearithmeticconversions,whichensurethatthetwooperandsofabinaryoperator,suchasanarithmeticorlogicaloperator,areconvertedtoacommontypebeforetheoperatorisevaluated。Thatcommontypeisalsotheresulttypeoftheexpression。
  C语言为内置类型提供了一组转换规则,其中最常用的是算术转换。算术转换保证在执行操作之前,将二元操作符(如算术或逻辑操作符)的两个操作数转换为同一类型,并使表达式的值也具有相同的类型。
  Therulesdefineahierarchyoftypeconversionsinwhichoperandsareconvertedtothewidesttypeintheexpression。Theconversionrulesaredefinedsoastopreservetheprecisionofthevaluesinvolvedinamultitypeexpression。Forexample,ifoneoperandisoftypelongdouble,thentheotherisconvertedtotypelongdoubleregardlessofwhatthesecondtypeis。
  算术转换规则定义了一个类型转换层次,该层次规定了操作数应按什么次序转换为表达式中最宽的类型。在包含多种类型的表达式中,转换规则要确保计算值的精度。例如,如果一个操作数的类型是longdouble,则无论另一个操作数是什么类型,都将被转换为longdouble。
  Thesimplestkindsofconversionareintegralpromotions。Eachoftheintegraltypesthataresmallerthanintchar,signedchar,unsignedchar,short,andunsignedshortispromotedtointifallpossiblevaluesofthattypefitinanint。Otherwise,thevalueispromotedtounsignedint。Whenboolvaluesarepromotedtoint,afalsevaluepromotestozeroandtruetoone。
  最简单的转换为整型提升:对于所有比int小的整型,包括char、signedchar、unsignedchar、short和unsignedshort,如果该类型的所有可能的值都能包容在int内,它们就会被提升为int型,否则,它们将被提升为unsignedint。如果将bool值提升为int,则false转换为0,而true则转换为1。
  需要注意的,上述所谓的转换只是运算时的类型转换,存储时还会转换为其声明时的类型。inta6;doubleb3。7;intsum;sumab;a会提升为double,ab的结果会由double降级为int给到sum,但a和sum的存储类型仍然不变
  1。2ConversionsbetweenSignedandUnsignedTypes有符号与无符号类型之间的转换
  Whenanunsignedvalueisinvolvedinanexpression,theconversionrulesaredefinedtopreservethevalueoftheoperands。Conversionsinvolvingunsignedoperandsdependontherelativesizesoftheintegraltypesonthemachine。Hence,suchconversionsareinherentlymachinedependent。
  若表达式中使用了无符号(unsigned)数值,所定义的转换规则需保护操作数的精度。unsigned操作数的转换依赖于机器中整型的相对大小,因此,这类转换本质上依赖于机器。
  Inexpressionsinvolvingshortsandints,valuesoftypeshortareconvertedtoint。Expressionsinvolvingunsignedshortareconvertedtointiftheinttypeislargeenoughtorepresentallthevaluesofanunsignedshort。Otherwise,bothoperandsareconvertedtounsignedint。Forexample,ifshortsareahalfwordandintsaword,thenanyunsignedvaluewillfitinsideanint。Onsuchamachine,unsignedshortsareconvertedtoint。
  包含short和int类型的表达式,short类型的值转换为int。如果int型足够表示所有unsignedshort型的值,则将unsignedshort转换为int,否则,将两个操作数均转换为unsignedint。例如,如果short用半字表示而int用一个字表示,则所有unsigned值都能包容在int内,在这种机器上,unsignedshort转换为int。
  Thesameconversionhappensamongoperandsoftypelongandunsignedint。Theunsignedintoperandisconvertedtolongiftypelongonthemachineislargeenoughtorepresentallthevaluesoftheunsignedint。Otherwise,bothoperandsareconvertedtounsignedlong。
  long和unsignedint的转换也是一样的。只要机器上的long型足够表示unsignedint型的所有值,就将unsignedint转换为long型,否则,将两个操作数均转换为unsignedlong。
  Ona32bitmachine,longandintaretypicallyrepresentedinaword。Onsuchmachines,expressionsinvolvingunsignedintsandlongsareconvertedtounsignedlong。
  在32位的机器上,long和int型通常用一个字长表示,因此当表达式包含unsignedint和long两种类型,其操作数都应转换为unsignedlong型。
  Conversionsforexpressionsinvolvingsignedandunsignedintcanbesurprising。Intheseexpressionsthesignedvalueisconvertedtounsigned。Forexample,ifwecompareaplainintandanunsignedint,theintisfirstconvertedtounsigned。Iftheinthappenstoholdanegativevalue,theresultwillbeconvertedasdescribedasbelows,withalltheattendantproblemsdiscussedthere。
  对于包含signed和unsignedint型的表达式,其转换可能出乎我们的意料。表达式中的signed型数值会被转换为unsigned型。例如,比较int型和unsignedint型的简单变量,系统首先将int型数值转换为unsignedint型,如果int型的值恰好为负数,其结果将以下述方法转换,并带来其所有副作用。Thetypeofanobjectdeterminesthevaluesthattheobjectcanhold。Thisfactraisesthequestionofwhathappenswhenonetriestoassignavalueoutsidetheallowablerangetoanobjectofagiventype。
  对象的类型决定对象的取值。这会引起一个疑问:当我们试着把一个超出其取值范围的值赋给一个指定类型的对象时,结果会怎样呢?
  Thecompilermustadjusttheoutofrangevaluesothatitwillfit。Thecompilerdoessobytakingtheremainderofthevaluemodulothenumberofdistinctvaluestheunsignedtargettypecanhold。Anobjectthatisan8bitunsignedchar,forexample,canholdvaluesfrom0through255inclusive。Ifweassignavalueoutsidethisrange,thecompileractuallyassignstheremainderofthevaluemodulo256。Forexample,wemightattempttoassignthevalue336toan8bitsignedchar。Ifwetrytostore336inour8bitunsignedchar,theactualvalueassignedwillbe80,because80isequalto336modulo256。
  编译器必须调整越界值使其满足要求。编译器会将该值对unsigned类型的可能取值数目求模,然后取所得值。比如8位的unsignedchar,其取值范围从0到255(包括255)。如果赋给超出这个范围的值,那么编译器将会取该值对256求模后的值。例如,如果试图将336存储到8位的unsignedchar中,则实际赋值为80,因为80是336对256求模后的值。
  (通常,编译器对于signed整型也是同样处理。)2WhenImplicitTypeConversionsOccur何时发生隐式类型转换
  Thecompilerappliesconversionsforbothbuiltinandclasstypeobjectsasnecessary。Implicittypeconversionstakeplaceinthefollowingsituations:
  编译器在必要时将类型转换规则应用到内置类型和类类型的对象上。在下列情况下,将发生隐式类型转换:
  Inexpressionswithoperandsofmixedtypes,thetypesareconvertedtoacommontype:
  在混合类型的表达式中,其操作数被转换为相同的类型:intival;doubledval;floatsumivaldvalivalconvertedtodouble
  Anexpressionusedasaconditionisconvertedtobool:
  用作条件的表达式被转换为bool类型:intival;if(ival)ivalconvertedtoboolwhile(cin)cinconvertedtobool
  Conditionsoccurasthefirstoperandoftheconditional(?:)operatorandastheoperand(s)tothelogicalNOT(!),logicalAND(),andlogicalOR()operators。Conditionsalsoappearintheif,while,for,anddowhilestatements。
  条件操作符(?:)中的第一个操作数以及逻辑非(!)、逻辑与()和逻辑或()的操作数都是条件表达式。出现在if、while、for和dowhile语句中的同样也是条件表达式。
  Anexpressionusedtoinitializeorassigntoavariableisconvertedtothetypeofthevariable:
  用一表达式初始化某个变量,或将一表达式赋值给某个变量,则该表达式被转换为该变量的类型:intival3。14;3。14convertedtointintip;ip0;theint0convertedtoanullpointeroftypeint
  Inaddition,implicitconversionsalsooccurduringfunctioncalls。
  另外,在函数调用中也可能发生隐式类型转换。3C强制转换类模板
  3。1staticcast
  Anytypeconversionthatthecompilerperformsimplicitlycanbeexplicitlyrequestedbyusingastaticcast:
  编译器隐式执行的任何类型转换都可以由staticcast显式完成:doubled97。0;castspecifiedtoindicatethattheconversionisintentionalcharchstaticcastchar(d);
  Suchcastsareusefulwhenassigningalargerarithmetictypetoasmallertype。Thecastinformsboththereaderoftheprogramandthecompilerthatweareawareofandarenotconcernedaboutthepotentiallossofprecision。Compilersoftengenerateawarningforassignmentsofalargerarithmetictypetoasmallertype。Whenweprovidetheexplicitcast,thewarningmessageisturnedoff。
  当需要将一个较大的算术类型赋值给较小的类型时,使用强制转换非常有用。此时,强制类型转换告诉程序的读者和编译器:我们知道并且不关心潜在的精度损失。对于从一个较大的算术类型到一个较小类型的赋值,编译器通常会产生警告。当我们显式地提供强制类型转换时,警告信息就会被关闭。
  Astaticcastisalsousefultoperformaconversionthatthecompilerwillnotgenerateautomatically。Forexample,wecanuseastaticcasttoretrieveapointervaluethatwasstoredinavoidpointer:
  如果编译器不提供自动转换,使用staticcast来执行类型转换也是很有用的。例如,下面的程序使用staticcast找回存放在void指针中的值:voidpd;ok:addressofanydataobjectcanbestoredinavoidok:convertsvoidbacktotheoriginalpointertypedoubledpstaticcastdouble(p);
  Whenwestoreapointerinavoidandthenuseastaticcasttocastthepointerbacktoitsoriginaltype,weareguaranteedthatthepointervalueispreserved。Thatis,theresultofthecastwillbeequaltotheoriginaladdressvalue。
  可通过staticcast将存放在void中的指针值强制转换为原来的指针类型,此时我们应确保保持指针值。也就是说,强制转换的结果应与原来的地址值相等。
  3。2constcast
  Aconstcast,asitsnameimplies,castsawaytheconstnessofitsexpression。Forexample,wemighthaveafunctionnamedstringcopythatwearecertainreads,butdoesnotwrite,itssingleparameteroftypechar。Ifwehaveaccesstothecode,thebestalternativewouldbetocorrectittotakeaconstchar。Ifthatisnotpossible,wecouldcallstringcopyonaconstvalueusingaconstcast:
  constcast,顾名思义,将转换掉表达式的const性质。例如,假设有函数stringcopy,只有唯一的参数,为char类型,我们对该函数只读不写。在访问该函数时,最好的选择是修改它让它接受constchar类型的参数。如果不行,可通过constcast用一个const值调用stringcopy函数:constcharpcstr;charpcstringcopy(constcastchar(pcstr));
  Onlyaconstcastcanbeusedtocastawayconstness。Usinganyoftheotherthreeformsofcastinthiscasewouldresultinacompiletimeerror。Similarly,itisacompiletimeerrortousetheconstcastnotationtoperformanytypeconversionotherthanaddingorremovingconst。
  只有使用constcast才能将const性质转换掉。在这种情况下,试图使用其他三种形式的强制转换都会导致编译时的错误。类似地,除了添加或删除const特性,用constcast符来执行其他任何类型转换,都会引起编译错误。
  3。3reinterpretcast
  Areinterpretcastgenerallyperformsalowlevelreinterpretationofthebitpatternofitsoperands。
  reinterpretcast通常为操作数的位模式提供较低层次的重新解释。
  Areinterpretcastisinherentlymachinedependent。Safelyusingreinterpretcastrequirescompletelyunderstandingthetypesinvolvedaswellasthedetailsofhowthecompilerimplementsthecast。
  reinterpretcast本质上依赖于机器。为了安全地使用reinterpretcast,要求程序员完全理解所涉及的数据类型,以及编译器实现强制类型转换的细节。
  在引入命名的强制类型转换操作符之前,显式强制转换用圆括号将类型括起来实现:charpc(char)ip;
  Theeffectofthiscastisthesameasusingthereinterpretcastnotation。However,thevisibilityofthiscastisconsiderablyless,makingitevenmoredifficulttotrackdowntheroguecast。
  效果与使用reinterpretcast符号相同,但这种强制转换的可视性比较差,难以跟踪错误的转换。
  Dependingonthetypesinvolved,anoldstylecasthasthesamebehaviorasaconstcast,astaticcast,orareinterpretcast。Whenusedwhereastaticcastoraconstcastwouldbelegal,anoldstylecastdoesthesameconversionastherespectivenamedcast。Ifneitherislegal,thenanoldstylecastperformsareinterpretcast。Forexample,wemightrewritethecastsfromtheprevioussectionlessclearlyusingoldstylenotation:
  旧式强制转换依赖于所涉及的数据类型,具有与constcast、staticcast和reinterpretcast一样的行为。在合法使用staticcast或constcast的地方,旧式强制转换提供了与各自对应的命名强制转换一样的功能。如果这两种强制转换均不合法,则旧式强制转换执行reinterpretcast功能。例如,我们可用旧式符号重写上一节的强制转换:intival;doubledval;ivalint(dval);staticcast:convertsdoubletointconstcharpcstr;stringcopy((char)pcstr);constcast:castsawayconstintip;charpc(char)ip;reinterpretcast:treatsintaschar
  Byusingacast,theprogrammerturnsoffordampensnormaltypechecking。WestronglyrecommendthatprogrammersavoidcastsandbelievethatmostwellformedCprogramscanbewrittenwithoutrelyingoncasts。
  强制类型转换关闭或挂起了正常的类型检查。强烈建议程序员避免使用强制类型转换,不依赖强制类型转换也能写出很好的C程序。4相关术语
  arithmeticconversion(算术转换)
  Aconversionfromonearithmetictypetoanother。Inthecontextofthebinaryarithmeticoperators,arithmeticconversionsusuallyattempttopreserveprecisionbyconvertingasmallertypetoalargertype(e。g。,smallintegraltypes,suchascharandshort,areconvertedtoint)。
  算术类型之间的转换。在使用二元算术操作符的地方,算术转换通常将较小的类型转换为较大的类型,以确保精度(例如,将小的整型char型和short型转换为int型)。
  dynamiccast
  Usedincombinationwithinheritanceandruntimetypeidentification。
  用于结合继承和运行时类型识别。
  implicitconversion(隐式类型转换)
  Aconversionthatisautomaticallygeneratedbythecompiler。Givenanexpressionthatneedsaparticulartypebuthasanoperandofadifferingtype,thecompilerwillautomaticallyconverttheoperandtothedesiredtypeifanappropriateconversionexists。
  编译器自动实现的类型转换。假设表达式需要某种特定类型的数值,但其操作数却是其他不同的类型,此时如果系统定义了适当的类型转换,编译器会自动根据转换规则将该操作数转换为需要的类型。
  integralpromotions(整型提升)
  Subsetofthestandardconversionsthattakeasmallerintegraltypetoitsmostcloselyrelatedlargertype。Integraltypes(e。g。short,char,etc。)arepromotedtointorunsignedint。
  整型提升是标准类型转换规则的子集,它将较小的整型转换为最接近的较大数据类型。整型(如short、char等)被提升为int型或unsignedint型。
  reinterpretcast
  Interpretsthecontentsoftheoperandasadifferenttype。Inherentlymachinedependentanddangerous。
  将操作数内容解释为另一种不同的类型。这类强制转换本质上依赖于机器,而且是非常危险的。
  staticcast
  Anexplicitrequestforatypeconversionthatthecompilerwoulddoimplicitly。Oftenusedtooverrideanimplicitconversionthatthecompilerwouldotherwiseperform。
  编译器隐式执行的任何类型转换都可以由staticcast显式完成。我们常常使用staticcast取代由编译器实现的隐式转换。
  End

兵马俑介绍作文【导语】兵马俑位于西安临潼区东7。5公里的骊山北面,它距离西安有37。5公里,是我国最雄伟的古代地下军事博物馆。下面关于兵马俑介绍作文,祝您生活愉快!【篇一】兵马俑从前有……感恩父亲节的句子父亲严肃的脸容和他的诚挚的爱却时时伴随着我,激励着我,小编收集了感恩父亲节的句子,欢迎阅读。感恩父亲节的句子1爸爸,不管您打过我也好,骂过我也好,我知道都是为了我好,恨铁……浅阅读,我们失去了什么?浅阅读,顾名思义,就是囫囵吞枣,一目十行的粗略的阅读。在读图时代里,追求视觉上冲击的我们,似乎忽略了很多东西。在这种竞争激烈的社会,白天是忙碌到近乎要死掉的应酬,晚……初二我与校训的故事征文【第一篇】我与校训的故事作文每当我们抬头走进校园时,映入眼帘的是四个醒目的大字:日进日新!ldquo;日进日新rdquo;是我校的校训,所谓ldquo;日进日新rdquo……C919未完成2021年交付任务,国产化只有60,为何叫国产首先这种提问方法就有问题:空客A380、波音787、丰田车都是法国、美国、日本纯国产的吗?罗马不是一天建成的,饭要一口口吃,路要一步步走。而且中国民航客机要与世界顶尖飞机……关于我的表弟的作文500字我的表弟今年六岁了,他有着胖嘟嘟的身子,圆乎乎的脸蛋,圆鼓鼓的胳膊腿儿,捏一把都是肉。表弟的胖跟他嘴馋有关,从小到大,他都是家里有名的馋嘴猫。今天,表弟来我家做客,大家一……小米12Pro现在买还是再等等12U?虽然今年小米12一口气发布了三款手机,但是最重磅的小米12Ultra并没有一起来(反而发布了12X)。这下很多人就开始犯难了,这是买12Pro还是等12U,着实有点纠结!12U……一场春雨优秀作文500字早上,我刚刚醒来就闻到了春雨的气息,我站在窗边看到了春雨宝宝在欢快地跳着美丽的舞蹈。看着绵绵的春雨降落在需要滋润的大地上,我情不自禁地背起了一首古诗:好雨知时节,当春乃发生,随……全球最大的电动汽车电池制造商宁德时代投10亿元成立新公司据企查查APP显示,1月9日,奉新时代志存新能源材料有限公司成立,注册资本10亿元人民币。经营范围包含:碳酸锂系列产品、锂电正极材料(国家有专项规定除外)及其他化工产品(……2022年物联网行业现状及发展前景分析近年来,物联网技术得以不断积累与升级,产业链也逐渐完善和成熟,加之受基础设施建设、基础性行业转型和消费升级等周期性因素的驱动,处于不同发展水平的领域和行业交替式地不断推进物联网……初中描写春天风景作文初中描写春天风景作文1我们送走了南方罕见的严冬,迎来了温暖的春天。今天,我们怀着渴望的心情,去大自然南宁市青秀山风景区,寻找美丽的春姑娘。看,车厢外,路边的小草探着……机构扎堆调研!四大产品线发展强劲宇信科技(300674。SZ智通财经APP讯,中国银行业IT解决方案市场领军企业宇信科技(300674。SZ)在1月9日接受调研时表示,目前在手订单基本代表能够代表了2022年大概的收入增长的趋势,从数据……
微信出手!这类行为,严厉打击近日,微信安全中心发布《关于治理微信个人账号恶意营销行为的公告》,全文如下:一直以来,微信始终保持对违法违规行为严厉打击的态度,努力为用户营造一个安全、绿色的使用环境。……燃油时代的日系霸主,砸2500亿转型电动车在席卷全球的电动化浪潮中,日系车企本是最不积极的一方。固守氢能路线,在电动化转型上投入的迟疑,让日系车企无论是技术还是销量,都远逊于其他电动车厂商。如今,随着特斯拉……关于以学做菜为主题的优秀作文学做西红柿炒蛋今天,妈妈教我学做西红柿炒蛋这道炒菜。我从冰箱拿了一个西红柿和两个鸡蛋。我先把西红柿洗干净,妈妈妈教我切成一小块一小块的。因为我是第一次切,所以切得大……母亲身上的两道伤疤六年级作文在我的记忆中,永远留着母亲肚皮上的两道血红的丑陋的伤疤生我和妹妹不得不留下的永恒的伤疤。记得,在2015年9月21日那天晚上,一家人在医院里,守在妈妈身边,在等待着妹妹的……新能源汽车补贴退坡是什么意思新能源汽车补贴退坡的意思是:在提供补贴的同时,根据新能源汽车发展,有计划、有明确目标的逐步减少补贴,和早期的扶上马,送一程的说法比较起来,有明确的时间节点和额度限制。进入……计算机行业动态国产EDA有望加速发展据彭博社,美国EDA(Electronicdesignautomation,电子设计自动化)软件公司新思科技(SNPSUS)因涉嫌向受到制裁的中国公司转让关键技术正在接受美国商……春节小学作文400字范文春节也叫过年。传说年是一只可以在陆地上和海洋里生活的大怪兽,它一般都在海里生活,等正月初一这一天,它就上岸来祸害老百姓,后来人们才知道这个恐怖的怪物怕红色、火光和响声,于是人们……2017关于熊猫的优秀作文集锦导语:熊猫听了大家的话,对小狗说:ldquo;我们别砍大树了,还是找些枯树来做桌子吧。rdquo;于是他们找来了枯树,小狗砍木头,熊猫钉钉子,做成了一张漂亮的桌子。下面是小编整……同桌的你作文400字五篇同桌,是一本永不泛黄的日记。以下是小编为大家推荐的同桌的你作文400字五篇,欢迎大家阅读!同桌的你作文一采荷二小迎来了新加坡美雅小学的部分老师和同学。在热情洋溢的欢迎仪式……德国或提前取消插电式混动车补贴来源:盖世汽车星云据外媒报道,据一位知情人士透露,德国经济部希望在今年年底提前结束针对插电式混合动力汽车的补贴,并从2023年起,将针对电动汽车的现金补贴减少三分之一。……索尼前CEO日企为何输给中国来源:环球时报日本PresidentOnline网站4月13日文章,原题:因此才会输给中国企业,索尼前首席执行官(CEO)担心的日本企业的大问题官僚依赖在日本经济处于低谷……自然中国将目光投向遥远的地球2。0英国《自然》杂志网站在4月12日的报道中指出,继将机器人送上月球、让机器人降落火星并建造自己的空间站之后,中国将目光投向了遥远的太阳系。4月,中国科学家将公布首个系外行星探测任……
友情链接:易事利快生活快传网聚热点七猫云快好知快百科中准网快好找文好找中准网快软网