简体   繁体   中英

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[] = ... .

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 . 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[] = ... ?

Starting with the introduction of stdint.h header in C99, there is no good reason to continue using char type to represent small numbers.

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. When you use char you cannot assume if it is signed or unsigned, because this behavior is implementation-defined.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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