简体   繁体   English

C:将字节数组声明为uint8_t是否有问题?

[英]C: Is there something wrong with declaring byte arrays as uint8_t?

I'm working on a small networking application that uses byte arrays. 我正在研究一个使用字节数组的小型网络应用程序。 Traditionally these would be declared with something like char buf[] = ... . 传统上这些将用char buf[] = ...

This seems to be how it is (still?) done in most tutorials, yet it has the problem that it may obscure what is actually happening, for example when you try to print such an array and forget that not every char is a visible character. 这似乎是在大多数教程中完成的(仍然?),但它有一个问题,它可能会模糊实际发生的事情,例如当你尝试打印这样的数组并忘记不是每个字符都是可见的字符。

Some people have suggested that you should stop using chars altogether and instead use the modern uint8_t . 有些人建议你应该完全停止使用chars ,而是使用现代的uint8_t I find that very appealing, mostly on the principle that explicit is better than implicit. 我发现这非常吸引人,主要是基于明确比隐含更好的原则。

So, is there something wrong with declaring these kinds of arrays as uint8_t buf[] = ... ? 因此,将这些类型的数组声明为uint8_t buf[] = ...是否有问题?

Starting with the introduction of stdint.h header in C99, there is no good reason to continue using char type to represent small numbers. 从在C99中引入stdint.h头开始,没有充分的理由继续使用char类型来表示小数字。

In addition to documenting your intentions better, uint8_t gives you one more important advantage: it guarantees that the byte is going to be treated as unsigned. 除了更好地记录您的意图之外, uint8_t为您提供了一个更重要的优势:它保证字节将被视为无符号。 When you use char you cannot assume if it is signed or unsigned, because this behavior is implementation-defined. 当您使用char您不能假设它是有符号还是无符号,因为此行为是实现定义的。

As far as inadvertent printing of the buffer goes, using uint8_t is not going to guarantee any protection, because on many platforms it's simply a typedef for unsigned char . 对于缓冲区的无意打印,使用uint8_t并不能保证任何保护,因为在许多平台上它只是unsigned chartypedef

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

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