Best Practices: Should I create a typedef for byte in C or C++?

前端 未结 6 1758
情歌与酒
情歌与酒 2021-02-07 05:40

Do you prefer to see something like t_byte* (with typedef unsigned char t_byte) or unsigned char* in code?

I\'m leaning towards

6条回答
  •  無奈伤痛
    2021-02-07 05:55

    I suggest that if your compiler supports it use the C99 header types such as uint8_t and int8_t.

    If your compiler does not support it, create one. Here's an example for VC++, older versions of which do not have stdint.h. GCC does support stdint.h, and indeed most of C99

    One problem with your suggestion is that the sign of char is implementation defined, so if you do create a type alias. you should at least be explicit about the sign. There is some merit in the idea since in C# for example a char is 16bit. But it has a byte type as well.


    Additional note...

    There was no problem with your suggestion, you did in fact specify unsigned.

    I would also suggest that plain char is used if the data is in fact character data, i.e. is a representation of plain text such as you might display on a console. This will present fewer type agreement problems when using standard and third-party libraries. If on the other hand the data represents a non-character entity such as a bitmap, or if it is numeric 'small integer' data upon which you might perform arithmetic manipulation, or data that you will perform logical operations on, then one of the stdint.h types (or even a type defined from one of them) should be used.

    I recently got caught out on a TI C54xx compiler where char is in fact 16bit, so that is why using stdint.h where possible, even if you use it to then define a byte type is preferable to assuming that unsigned char is a suitable alias.

提交回复
热议问题