简体   繁体   English

我应该在括号之间写什么来定义我希望变量更改为的数据类型?

[英]What should I write in between parentheses to define the data type I want a variable to change to?

If I have a variable as float var1 = 157.1;如果我有一个变量作为float var1 = 157.1; and want to transform it in int I would do int var2 = (int)var1;并想将其转换为 int 我会做int var2 = (int)var1;

I want to know about the other types of data, such as long int , short int , unsigned short int , long double and so on.我想了解其他类型的数据,例如long intshort intunsigned short intlong double等。

I tried long int var2 = (long int)var1;我试过long int var2 = (long int)var1; and it seemed to work, but I'm not sure if it is syntactically correct.它似乎有效,但我不确定它在语法上是否正确。 If it is, I assume it'd be the same for all the other types, ie, just the data type and its attributes separated by a space.如果是,我假设所有其他类型都相同,即数据类型及其属性由空格分隔。 If it isn't I'd like to know if there's a list of them of some sort.如果不是,我想知道是否有某种列表。

This is the C cast operator, but the operation is more generally "type casting", "casting", or "recasting".这是 C 铸造运算符,但操作更普遍的是“类型铸造”、“铸造”或“重铸”。 This is a directive to the compiler to request a specific conversion.这是编译器请求特定转换的指令。

When casting any valid C type can be specified, so:铸造时可以指定任何有效的 C 类型,因此:

int x = 10;
unsigned long long y = (unsigned long long) x;

In many cases this conversion can be done implicitly, automatically, so it's not always necessary but in others you must force it.在许多情况下,这种转换可以隐式地、自动地完成,所以它并不总是必要的,但在其他情况下,你必须强制它。 For example:例如:

int x = 10;
float y = x; // Valid, int -> float happens automatically.

You can get caught by surprise though:但是,您可能会感到惊讶:

int x = 10;
float y = x / 3; // y = 3.0, not 3.333, since it does integer division before casting

Where you need to cast to get the right result:您需要在哪里进行转换以获得正确的结果:

int x = 10;
float y = (float) x / 3; // 3.33333...

Note that when using pointers this is a whole different game:请注意,当使用指针时,这是一个完全不同的游戏:

int x = 10;
int* px = &x;
float* y = (float*) px; // Invalid conversion, treats int as a float

Generally C trusts you to know what you're doing, so you can easily shoot yourself in the foot.通常 C 相信您知道自己在做什么,因此您可以轻松地射中自己的脚。 What "compiles" is syntactically valid by definition, but executing properly without crashing is a whole other concern.根据定义,“编译”在语法上是有效的,但正确执行而不会崩溃是另一个问题。 Anything not specified by the C "rule book" (C standard) is termed undefined behaviour , so you'll need to be aware of when you're breaking the rules, like in that last example. C“规则手册”(C 标准)未指定的任何内容都称为未定义行为,因此您需要注意何时违反规则,就像最后一个示例中一样。

Sometimes breaking the rules is necessary, like the Fast Inverse Square Root which relies on the ability of C to arbitrarily recast values.有时打破规则是必要的,例如快速平方根平方根,它依赖于 C 任意重铸值的能力。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM