1

Is it a good code style to cast -1 to unsigned int? For example:

#define MAX_UINT8 ((uint8_t) -1)

comparing to

#define MAX_UINT8 0xff
Gnimuc
  • 8,098
  • 2
  • 36
  • 50
  • 12
    Casting `-1` to unsigned type is OK but defining `MAX_UINT8` by yourself is bad. You should use `UINT8_MAX` from `stdint.h`. – MikeCAT May 14 '21 at 11:45
  • 1
    You may want to read this link: [Fixed width integer types](https://en.cppreference.com/w/c/types/integer) – Andreas Wenzel May 14 '21 at 11:50
  • `uint8_t someVariable=0xFF;` is the most clear version for me. The max value of `0xFF` for a 8 bit unsigned int is not going to change. – 12431234123412341234123 May 14 '21 at 11:50
  • 1
    In general, it's a bad idea to create your own definitions for type limits because C has the [potential for subtleties and strange corner cases when limits are involved](https://stackoverflow.com/questions/14695118/2147483648-0-returns-true-in-c). – Andrew Henle May 14 '21 at 12:38

1 Answers1

5

Style and usefulness

Is it a good code style to cast -1 to unsigned int?

Not when coding the maximum uint8_t.
Use UINT8_MAX from inttypes.h @MikeCAT

#define MAX_UINT8 0xff is OK for pre-processor operations. Do not rely on casts with pre-processor math. Thus #define MAX_UINT8 ((uint8_t) -1) is less useful (and could lead to unexpected pre-processing) than #define MAX_UINT8 0xff

Try

#include <stdint.h>
#define MAX_UINT8 ((uint8_t) -1)

#if MAX_UINT8 < 0
#error "MAX_UINT8 < 0"
#endif

Type Differences

((uint8_t) -1) is usually type unsigned char. uint8_t is an optional type1, yet very commonly implemented.

0xff is type int.

Using one or the other leads to a difference with _Generic and sizeof.


1uintN_t

These types are optional. However, if an implementation provides integer types with widths of 8, 16, 32, or 64 bits, no padding bits, and (for the signed types) that have a two’s complement representation, it shall define the corresponding typedef names.
C17dr § 7.20.1.1 3

chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256
  • `uint8_t` is only "optional" in the sense that having 8-bit types is optional -- if char is 8-bit then this type must exist. So it can be a good idea to use it as a way to encode that your program is rejected by implementations without 8-bit char. – M.M May 14 '21 at 11:54
  • @M.M ... and no padding bits with the signed types represented in twos-complement. – Andrew Henle May 14 '21 at 12:34