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

I am working on a small network application that uses byte arrays. Traditionally, they will be announced with something like char buf[] = ....

It seems that this (still?) Has been done in most textbooks, but it has a problem that it can 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 suggested that you should completely stop using it charsand use a modern one instead uint8_t. I find it very attractive, mainly on the principle that explicit is better than implicit.

So, is there something wrong with declaring these array types as uint8_t buf[] = ...?

+4
source share
1 answer

Since the introduction of the heading stdint.hon C99, there is no good reason to continue to use the type charto represent small numbers.

In addition to documenting your intentions better, uint8_tgives you another important advantage: it ensures that the byte will be treated as unsigned. When you use char, you cannot assume that it is signed or unsigned because this behavior is determined by the implementation.

As the inadvertent printing of the buffer occurs, use uint8_tdoes not guarantee any protection, because on many platforms it is easy typedeffor unsigned char.

+3
source

Source: https://habr.com/ru/post/1690718/


All Articles