堃怎么读什么意思| 亚甲炎是什么原因引起的| 孕妇吃什么是补铁的| 湿热喝什么茶可以调理| 醒酒器有什么作用| 右额头上有痣代表什么| 双鱼和什么星座最配| ab制是什么意思| 冬天种什么蔬菜合适| 什么药和酒一起吃必死| 甲亢有什么症状| 翡翠戴久了会有什么变化| gtp什么意思| 尿酸高会引发什么疾病| hco3-是什么意思| 栓塞是什么意思| 正月初二是什么星座的| 腰椎间盘突出看什么科| 抑郁症发作是什么感觉| 托梦是什么意思| 凶狠的反义词是什么| b27是什么检查| 拉肚子吃什么水果| 儿童便秘吃什么最管用| 汉语拼音是什么时候发明的| 果位是什么意思| 楚国是现在的什么地方| 属实是什么意思| 士字五行属什么| 什么是耦合| 什么米最贵| 属猴和什么属相相冲| 升血小板吃什么药| 感冒流清水鼻涕吃什么药| 黑咖啡为什么能减肥| hpv阳性意味着什么| 牙龈和牙齿分离是什么原因| 牙根痛吃什么药| 肛裂是什么样子的图片| 复仇者用什么武器| 湿疹是什么症状及图片| 上梁山是什么意思| 裳能组什么词| 老鸨是什么意思| 1949年是什么年| 痿是什么意思| 小肠ct能检查什么病| 什么是白细胞| 为什么一动就出汗| 正确的三观是什么| 生僻字什么意思| 拔牙前需要做什么检查| 痛经吃什么水果| 五红汤什么时候喝最好| 嫩绿的什么| 精神衰弱吃什么药| 黄疸高对婴儿有什么影响| 名字五行属什么| 生化全套主要检查什么| 容易脸红的人是什么原因| 不完全骨折是什么意思| 确幸是什么意思| 脾肾阳虚是什么意思| 菠萝蜜不能跟什么一起吃| 09年的牛是什么命| 51岁属什么生肖| 奢侈品是什么意思| 天外飞仙是什么意思| 归是什么意思| 什么是低保| 支原体感染是什么意思| 吃火龙果对身体有什么好处| 不什么| 气血两虚是什么意思| timing是什么意思| 被蚂蚁咬了涂什么药| seiko是什么牌子| 淋雨了喝什么驱寒| 面试要带什么| 肝阴虚吃什么中成药| 眼睛上火用什么眼药水| 欠钱不还被起诉会有什么后果| 老年人吃什么营养品好| 什么是av| 淋巴是什么东西| 淤血是什么意思| 孕妇梦见很多蛇是什么意思| 上午十点到十一点是什么时辰| 次数是什么| 发烧了吃什么食物好| 口腔上颚疼是什么原因| 读书心得是什么意思| 益生元是什么| 职位是什么意思| 手足口病咳嗽吃什么药| 泥鳅不能和什么一起吃| 尿酸高吃什么中药能降下来| 艾司唑仑片是什么药| 炁读什么| 灵芝长什么样子| 埃及艳后叫什么| 孩子多动缺什么| 虫字旁与什么有关| 植物的茎有什么作用| 肌酐什么意思| 头发掉是什么原因引起的| 脉压差小是什么原因| 智齿是什么意思| 福星是什么意思| 枯草芽孢杆菌治什么病| 强迫思维是什么| 讲师是什么职称| o和ab型生的孩子是什么血型| 胆红素三个指标都高是什么原因| 鳗鱼吃什么食物| 甲状腺挂什么科| 川芎治什么病最好| 气压是什么| 双子座男生喜欢什么样的女生| 三月初六是什么星座| nasa是什么意思| 出栏是什么意思| 辣的部首是什么| 直接胆红素是什么| 梵克雅宝为什么那么贵| 切片是什么意思| 入党有什么用| 消瘦是什么意思| 中性粒细胞高说明什么| 农历八月初一是什么星座| 水母是什么| 冠带什么意思| 备孕为什么要吃叶酸| 痔疮手术后可以吃什么水果| 杭州什么宽带好又便宜| 4月30号是什么星座| 肝气犯胃吃什么中成药| 孩子打嗝是什么原因| 风疹吃什么药| 王牌是什么意思| 梅干菜是什么菜| 心悸心慌是什么原因| 浓度是什么意思| 什么是远视| 太监是什么| 胃炎伴糜烂吃什么药效果好| 荔枝有什么好处| 龟头上抹什么可以延时| 郑州有什么好吃的| 钧什么意思| 苎麻是什么面料| 子宫瘢痕憩室是什么病| 化橘红是什么东西| 43是什么意思| 经常性偏头疼是什么原因| 局气是什么意思| 楔形是什么形状图片| 癫疯病发作前兆有什么症状| 向日葵是什么意思| 惠什么意思| 神经性皮炎用什么药膏效果最好| 万言万当不如一默是什么意思| 为什么不建议小孩吃罗红霉素| 梵文是什么意思| 宝宝积食吃什么| 自由行是什么意思| 梦见狗追我是什么意思| 肝实质回声欠均匀是什么意思| 什么样的小鱼| 下腹部胀是什么原因| 扁桃体发炎是什么引起的| 甘油三酯指的是什么| 唐氏筛查和无创有什么区别| 甘油三酯高会引起什么病| 高温天气喝什么茶解暑| 5月31日是什么星座| 什么是舒张压和收缩压| 血管夹层是什么病| 营养科都检查什么项目| 每天早上起床头晕是什么原因| 五音指什么| 南屏晚钟什么意思| 时尚是什么意思| 为什么月经来是黑色的| 马齿苋煮水喝有什么功效| 牛肉和什么不能一起吃| 总蛋白高是什么原因| 常务副县长什么级别| 什么是二级医院| 晚上两点是什么时辰| 同人小说是什么意思| 阴虚火旺吃什么食物| 小孩急性肠胃炎吃什么药| 什么什么什么心| 金晨什么星座| epc是什么意思| 胰岛素是什么| 葡萄糖偏低是什么意思| 吃什么容易胖| 五月二十四号是什么星座| 什么筷子不发霉又健康| 回头是岸是什么生肖| seconds是什么意思| 7一9点是什么时辰| 无名指是什么经络| 10月1日是什么日子| 南昌有什么好玩的地方| 房性期前收缩是什么意思| 眩晕挂什么科| 红细胞偏高是什么病| 冥界是什么意思| 你代表什么意思| 早上六点是什么时辰| 猫的胡子有什么作用| 什么菜不能放醋| 谈情说爱是什么意思| 小孩放屁很臭是什么原因| 叶酸片什么时候吃| 囊性病变是什么意思| 肩周炎用什么药好| 星月菩提五行属什么| 大学毕业送什么花| 过敏了吃什么药| l do是什么意思| 长子是什么意思| 老是肚子疼是什么原因| 美食家是什么意思| 石花膏是什么做的| 吃什么降火| 男性霉菌感染用什么药| 为什么会气血不足| 食伤泄秀是什么意思| 12月3日什么星座| 肝内胆管结石吃什么药好| 巨蟹女和什么星座最配| 火龙果什么时候成熟| 什么原因引起耳鸣| 米诺地尔搽剂和米诺地尔酊有什么区别| 胆汁反流是什么原因| 七月七是什么节日| 女红是什么意思| 女人出汗多是什么原因| 蒋字五行属什么| 看到壁虎是什么征兆| 宫腔粘连有什么危害| 右手无名指戴戒指代表什么| 66年属马是什么命| 天珺手表什么档次| 阳寿是什么意思| 睡觉时胳膊和手发麻是什么原因| 96年属什么命| 再接再励是什么意思| 艾滋病阳性是什么意思| 11月30号是什么星座| 梦见摘桑葚是什么意思| 夏天摆摊适合卖什么| 全是什么意思| 什么牌子的点读机好| 得了梅毒会有什么症状| carol什么意思| 扁桃体切除有什么坏处| 天上的彩虹像什么| 狗狗怀孕吃什么| 肠道消炎用什么药最好| 百度Jump to content

Globalization still the key to prosperity, equality IMF’s Lagarde

From Wikipedia, the free encyclopedia
(Redirected from Type coercion)
百度 截止上午9点钟,仅为了“谁当主席”,蓝绿双方就爆发了两次肢体冲突。

In computer science, type conversion,[1][2] type casting,[1][3] type coercion,[3] and type juggling[4][5] are different ways of changing an expression from one data type to another. An example would be the conversion of an integer value into a floating point value or its textual representation as a string, and vice versa. Type conversions can take advantage of certain features of type hierarchies or data representations. Two important aspects of a type conversion are whether it happens implicitly (automatically) or explicitly,[1][6] and whether the underlying data representation is converted from one representation into another, or a given representation is merely reinterpreted as the representation of another data type.[6][7] In general, both primitive and compound data types can be converted.

Each programming language has its own rules on how types can be converted. Languages with strong typing typically do little implicit conversion and discourage the reinterpretation of representations, while languages with weak typing perform many implicit conversions between data types. Weak typing language often allow forcing the compiler to arbitrarily interpret a data item as having different representations—this can be a non-obvious programming error, or a technical method to directly deal with underlying hardware.

In most languages, the word coercion is used to denote an implicit conversion, either during compilation or during run time. For example, in an expression mixing integer and floating point numbers (like 5 + 0.1), the compiler will automatically convert integer representation into floating point representation so fractions are not lost. Explicit type conversions are either indicated by writing additional code (e.g. adding type identifiers or calling built-in routines) or by coding conversion routines for the compiler to use when it otherwise would halt with a type mismatch.

In most ALGOL-like languages, such as Pascal, Modula-2, Ada and Delphi, conversion and casting are distinctly different concepts. In these languages, conversion refers to either implicitly or explicitly changing a value from one data type storage format to another, e.g. a 16-bit integer to a 32-bit integer. The storage needs may change as a result of the conversion, including a possible loss of precision or truncation. The word cast, on the other hand, refers to explicitly changing the interpretation of the bit pattern representing a value from one type to another. For example, 32 contiguous bits may be treated as an array of 32 Booleans, a 4-byte string, an unsigned 32-bit integer or an IEEE single precision floating point value. Because the stored bits are never changed, the programmer must know low level details such as representation format, byte order, and alignment needs, to meaningfully cast.

In the C family of languages and ALGOL 68, the word cast typically refers to an explicit type conversion (as opposed to an implicit conversion), causing some ambiguity about whether this is a re-interpretation of a bit-pattern or a real data representation conversion. More important is the multitude of ways and rules that apply to what data type (or class) is located by a pointer and how a pointer may be adjusted by the compiler in cases like object (class) inheritance.

Explicit casting in various languages

[edit]

Ada

[edit]

Ada provides a generic library function Unchecked_Conversion.[8]

C-like languages

[edit]

Implicit type conversion

[edit]

Implicit type conversion, also known as coercion or type juggling, is an automatic type conversion by the compiler. Some programming languages allow compilers to provide coercion; others require it.

In a mixed-type expression, data of one or more subtypes can be converted to a supertype as needed at runtime so that the program will run correctly. For example, the following is legal C language code:

double  d;
long    l;
int     i;

if (d > i)   d = i;
if (i > l)   l = i;
if (d == l)  d *= 2;

Although d, l, and i belong to different data types, they will be automatically converted to equal data types each time a comparison or assignment is executed. This behavior should be used with caution, as unintended consequences can arise. Data can be lost when converting representations from floating-point to integer, as the fractional components of the floating-point values will be truncated (rounded toward zero). Conversely, precision can be lost when converting representations from integer to floating-point, since a floating-point type may be unable to exactly represent all possible values of some integer type. For example, float might be an IEEE 754 single precision type, which cannot represent the integer 16777217 exactly, while a 32-bit integer type can. This can lead to unintuitive behavior, as demonstrated by the following code:

#include <stdio.h>

int main(void)
{
    int i_value   = 16777217;
    float f_value = 16777216.0;
    printf("The integer is: %d\n", i_value);
    printf("The float is:   %f\n", f_value);
    printf("Their equality: %d\n", i_value == f_value);
}

On compilers that implement floats as IEEE single precision, and ints as at least 32 bits, this code will give this peculiar print-out:

The integer is: 16777217
The float is: 16777216.000000
Their equality: 1

Note that 1 represents equality in the last line above. This odd behavior is caused by an implicit conversion of i_value to float when it is compared with f_value. The conversion causes loss of precision, which makes the values equal before the comparison.

Important takeaways:

  1. float to int causes truncation, i.e., removal of the fractional part.
  2. double to float causes rounding of digit.
  3. long to int causes dropping of excess higher order bits.
Type promotion
[edit]

One special case of implicit type conversion is type promotion, where an object is automatically converted into another data type representing a superset of the original type. Promotions are commonly used with types smaller than the native type of the target platform's arithmetic logic unit (ALU), before arithmetic and logical operations, to make such operations possible, or more efficient if the ALU can work with more than one type. C and C++ perform such promotion for objects of Boolean, character, wide character, enumeration, and short integer types which are promoted to int, and for objects of type float, which are promoted to double. Unlike some other type conversions, promotions never lose precision or modify the value stored in the object.

In Java:

int x = 3;
double y = 3.5;
System.out.println(x + y); // The output will be 6.5

Explicit type conversion

[edit]

Explicit type conversion, also called type casting, is a type conversion which is explicitly defined within a program (instead of being done automatically according to the rules of the language for implicit type conversion). It is requested by the user in the program.

double da = 3.3;
double db = 3.3;
double dc = 3.4;
int result = (int)da + (int)db + (int)dc; // result == 9
// if implicit conversion would be used (as with "result = da + db + dc"), result would be equal to 10

There are several kinds of explicit conversion.

checked
Before the conversion is performed, a runtime check is done to see if the destination type can hold the source value. If not, an error condition is raised.
unchecked
No check is performed. If the destination type cannot hold the source value, the result is undefined.
bit pattern
The raw bit representation of the source is copied verbatim, and it is re-interpreted according to the destination type. This can also be achieved via aliasing.

In object-oriented programming languages, objects can also be downcast : a reference of a base class is cast to one of its derived classes.

C# and C++

[edit]

In C#, type conversion can be made in a safe or unsafe (i.e., C-like) manner, the former called checked type cast.[9]

Animal animal = new Cat();

Bulldog b = (Bulldog) animal;  // if (animal is Bulldog), stat.type(animal) is Bulldog, else an exception
b = animal as Bulldog;         // if (animal is Bulldog), b = (Bulldog) animal, else b = null

animal = null;
b = animal as Bulldog;         // b == null

In C++ a similar effect can be achieved using C++-style cast syntax.

Animal* animal = new Cat;

Bulldog* b = static_cast<Bulldog*>(animal); // compiles only if either Animal or Bulldog is derived from the other (or same)
b = dynamic_cast<Bulldog*>(animal);         // if (animal is Bulldog), b = (Bulldog*) animal, else b = nullptr

Bulldog& br = static_cast<Bulldog&>(*animal); // same as above, but an exception will be thrown if a nullptr was to be returned
                                              // this is not seen in code where exception handling is avoided

delete animal; // always free resources
animal = nullptr;
b = dynamic_cast<Bulldog*>(animal);         // b == nullptr

Eiffel

[edit]

In Eiffel the notion of type conversion is integrated into the rules of the type system. The Assignment Rule says that an assignment, such as x := y, is valid if and only if the type of its source expression (y) is compatible with the type of its target entity (x). In this rule, compatible with means that the type of the source expression either conforms to or converts to that of the target. Conformance of types is defined by the rules for polymorphism in object-oriented programming. For example, in the assignment above, the type of y conforms to the type of x if the class upon which y is based is a descendant of that upon which x is based.

Rust

[edit]

Rust provides no implicit type conversion (coercion) between most primitive types. But, explicit type conversion (casting) can be performed using the as keyword.[10]

let x = 1000;
println!("1000 as a u16 is: {}", x as u16);

Type assertion

[edit]

A related concept in static type systems is called type assertion, which instruct the compiler to treat the expression of a certain type, disregarding its own inference. Type assertion may be safe (a runtime check is performed) or unsafe. A type assertion does not convert the value from a data type to another.

TypeScript

[edit]

In TypeScript, a type assertion is done by using the as keyword:[11]

const myCanvas = document.getElementById("main_canvas") as HTMLCanvasElement;

In the above example, document.getElementById is declared to return an HTMLElement, but you know that it always return an HTMLCanvasElement, which is a subtype of HTMLElement, in this case. If it is not the case, subsequent code which relies on the behaviour of HTMLCanvasElement will not perform correctly, as in Typescript there is no runtime checking for type assertions.

In Typescript, there is no general way to check if a value is of a certain type at runtime, as there is no runtime type support. However, it is possible to write a user-defined function which the user tells the compiler if a value is of a certain type of not. Such a function is called type guard, and is declared with a return type of x is Type, where x is a parameter or this, in place of boolean.

This allows unsafe type assertions to be contained in the checker function instead of littered around the codebase.

Go

[edit]

In Go, a type assertion can be used to access a concrete type value from an interface value. It is a safe assertion that it will panic (in the case of one return value), or return a zero value (if two return values are used), if the value is not of that concrete type.[12]

t := i.(T)

This type assertions tell the system that i is of type T. If it isn't, it panics.

Implicit casting using untagged unions

[edit]

Many programming languages support union types which can hold a value of multiple types. Untagged unions are provided in some languages with loose type-checking, such as C and PL/I, but also in the original Pascal. These can be used to interpret the bit pattern of one type as a value of another type.

Security issues

[edit]

In hacking, typecasting is the misuse of type conversion to temporarily change a variable's data type from how it was originally defined.[13] This provides opportunities for hackers since in type conversion after a variable is "typecast" to become a different data type, the compiler will treat that hacked variable as the new data type for that specific operation.[14]

See also

[edit]

References

[edit]
  1. ^ a b c Mehrotra, Dheeraj (2008). S. Chand's Computer Science. S. Chand. pp. 81–83. ISBN 978-8121929844.
  2. ^ Programming Languages - Design and Constructs. Laxmi Publications. 2013. p. 35. ISBN 978-9381159415.
  3. ^ a b Reilly, Edwin (2004). Concise Encyclopedia of Computer Science. John Wiley & Sons. pp. 82, 110. ISBN 0470090952.
  4. ^ Fenton, Steve (2017). Pro TypeScript: Application-Scale JavaScript Development. Apress. pp. xxiii. ISBN 978-1484232491.
  5. ^ "Type Juggling". PHP Manual. Retrieved 27 January 2019.
  6. ^ a b Olsson, Mikael (2013). C++ Quick Syntax Reference. Apress. pp. 87–89. ISBN 978-1430262770.
  7. ^ Kruse, Rudolf; Borgelt, Christian; Braune, Christian; Mostaghim, Sanaz; Steinbrecher, Matthias (16 September 2016). Computational Intelligence: A Methodological Introduction. Springer. p. 269. ISBN 978-1447172963.
  8. ^ "Unchecked Type Conversions". Ada Information Clearinghouse. Retrieved 11 March 2023.
  9. ^ M?ssenb?ck, Hanspeter (25 March 2002). "Advanced C#: Checked Type Casts" (PDF). Institut für Systemsoftware, Johannes Kepler Universit?t Linz, Fachbereich Informatik. p. 5. Retrieved 4 August 2011. at C# Tutorial
  10. ^ "Casting". Rust by Example. Retrieved 1 April 2025.
  11. ^ "Everyday Types". The TypeScript Handbook. Retrieved 1 April 2025.
  12. ^ "Type assertions". A Tour of Go. Retrieved 1 April 2025.
  13. ^ Erickson, Jon (2008). Hacking: The Art of Exploitation. No Starch Press. p. 51. ISBN 978-1-59327-144-2. "Typecasting is simply a way to temporarily change a variable's data type, despite how it was originally defined. When a variable is typecast into a different type, the compiler is basically told to treat that variable as if it were the new data type, but only for that operation. The syntax for typecasting is as follows: (typecast_data_type) variable ..."
  14. ^ Gopal, Arpita (2009). Magnifying C. PHI Learning Private Limited. p. 59. ISBN 978-81-203-3861-6. "From the above, it is clear that the usage of typecasting is to make a variable of one type, act like another type for one single operation. So by using this ability of typecasting it is possible for create ASCII characters by typecasting integer to its ..."
[edit]
女人的网名叫什么好听 梦见找鞋子是什么意思 每天喝牛奶有什么好处 毒瘤是什么意思 面瘫是什么原因造成的
七月四日是什么星座 幽门螺杆菌是什么 亢进是什么意思 海参多少头是什么意思 本来无一物何处惹尘埃是什么意思
ivd是什么意思 白藜芦醇是什么东西 征求是什么意思 盆腔积液吃什么药效果最好 查肝胆胰脾肾挂什么科
孕妇忌吃什么 种牙好还是镶牙好区别是什么 梦见大蜈蚣是什么预兆 心脏支架后吃什么药 舌头上有白苔是什么原因
耳朵堵塞感是什么原因hcv9jop1ns7r.cn 检验科是做什么的hcv9jop4ns1r.cn 噩梦是什么意思hcv8jop2ns2r.cn 木耳中毒什么症状hcv9jop0ns3r.cn 二大爷是什么意思creativexi.com
减肥早餐吃什么最好hcv8jop1ns3r.cn 地什么人什么hlguo.com 热感冒有什么症状hcv9jop1ns1r.cn 严密是什么意思hcv8jop4ns2r.cn 铁锈色痰见于什么病helloaicloud.com
柠檬酸钠是什么hcv8jop7ns3r.cn 哺乳期吃什么水果hcv9jop2ns1r.cn 罗汉果有什么功效和作用imcecn.com 什么程度算节食减肥bfb118.com 儿童咳嗽吃什么药hcv7jop9ns3r.cn
poison是什么意思hcv7jop9ns2r.cn 基础代谢是什么hcv9jop1ns1r.cn 马头琴是什么族的乐器hcv8jop9ns1r.cn 做脑ct对人体有什么危害0735v.com 儿童红眼病用什么眼药水hcv9jop3ns8r.cn
百度