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

900 Views Asked by At

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

1

There are 1 best solutions below

1
On BEST ANSWER

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.