简体   繁体   English

省略数据类型(例如“ unsigned”而不是“ unsigned int”)

[英]Omitting the datatype (e.g. “unsigned” instead of “unsigned int”)

I know that if the data type declaration is omitted in C/C++ code in such way: unsigned test=5; 我知道如果在C / C ++代码中以这种方式省略数据类型声明: unsigned test=5; , the compiler automatically makes this variable an int (an unsigned int in this case). ,编译器会自动将此变量设为int(在这种情况下为unsigned int)。 I've heard that it's a C standard and it will work in all compilers. 我听说这是C标准,它将在所有编译器中正常工作。

But I've also heard that doing this is considered a bad practice. 但是我也听说这样做是一种不好的做法。

What do you think? 你怎么看? Should I really type unsigned int instead of just unsigned ? 我应该真的输入unsigned int而不是unsigned吗?

Are short , long and long long also datatypes? shortlonglong long也是数据类型吗?

unsigned is a data type ! unsigned 是数据类型 And it happens to alias to unsigned int . 碰巧是unsigned int别名。

When you're writing unsigned x; 当您编写unsigned x; you are not omitting any data type. 不会忽略任何数据类型。

This is completely different from “default int ” which exists in C (but not in C++!) where you really omit the type on a declaration and C automatically infers that type to be int . 这与C(但C ++中没有)中的“ default int ”完全不同,在C中您实际上省略了声明中的类型,C会自动推断出该类型为int

As for style, I personally prefer to be explicit and thus to write unsigned int . 至于样式,我个人更喜欢露骨,因此写unsigned int On the other hand, I'm currently involved in a library where it's convention to just write unsigned , so I do that instead. 另一方面,我目前正在使用一个库,习惯上只写unsigned ,所以我改为这样做。

I would even take it one step further and use stdint 's uint32_t type. 我什至更进一步,并使用stdint的uint32_t类型。
It might be a matter of taste, but I prefer to know what primitive I'm using over some ancient consideration of optimising per platform. 这可能是一个问题,但是我宁愿知道我正在使用什么原始语言,而不是出于对每个平台进行优化的古老考虑。

As @Konrad Rudolph says, unsigned is a datatype. 正如@Konrad Rudolph所说, unsigned 数据类型。 It's really just an alias for unsigned int . 它实际上只是unsigned int的别名。

As to the question of using unsigned being bad practice? 至于使用unsigned的问题是不好的做法? I would say no, there is nothing wrong with using unsigned as a datatype specifier. 我会说不,使用unsigned作为数据类型说明符没有任何问题。 Professionals won't be thrown by this, and any coding standard that says you have to use unsigned int is needlessly draconian, in my view. 在我看来,专业人士不会为此而烦恼,任何说您必须使用unsigned int编码标准都是不必要的严厉。

Gratuitous verbosity considered harmful. 无谓的冗长被认为是有害的。 I would never write unsigned int or long int or signed anything (except char or bitfields) because it increases clutter and decreases the amount of meaningful code you can fit in 80 columns. 我永远不会写unsigned intlong int或任何signedchar或bitfield除外),因为它会增加混乱并减少可容纳80列的有意义代码的数量。 (Or more likely, encourages people to write code that does not fit in 80 columns...) (或更可能的是,鼓励人们编写不适合80列的代码...)

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

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