When should I just use “int” versus more sign-specific or size-specific types?

前端 未结 5 471
眼角桃花
眼角桃花 2021-01-30 06:18

I have a little VM for a programming language implemented in C. It supports being compiled under both 32-bit and 64-bit architectures as well as both C and C++.

I\'m try

5条回答
  •  余生分开走
    2021-01-30 07:08

    Here are a few things I do. Not sure they're for everyone but they work for me.

    1. Never use int or unsigned int directly. There always seems to be a more appropriately named type for the job.
    2. If a variable needs to be a specific width (e.g. for a hardware register or to match a protocol) use a width-specific type (e.g. uint32_t).
    3. For array iterators, where I want to access array elements 0 thru n, this should also be unsigned (no reason to access any index less than 0) and I use one of the fast types (e.g. uint_fast16_t), selecting the type based on the minimum size required to access all array elements. For example, if I have a for loop that will iterate through 24 elements max, I'll use uint_fast8_t and let the compiler (or stdint.h, depending how pedantic we want to get) decide which is the fastest type for that operation.
    4. Always use unsigned variables unless there is a specific reason for them to be signed.
    5. If your unsigned variables and signed variables need to play together, use explicit casts and be aware of the consequences. (Luckily this will be minimized if you avoid using signed variables except where absolutely necessary.)

    If you disagree with any of those or have recommended alternatives please let me know in the comments! That's the life of a software developer... we keep learning or we become irrelevant.

提交回复
热议问题