When to use size_t vs uint32_t? I saw a a method in a project that receives a parameter called length (of type uint32_t) to denote the length of byte data to deal with and the method is for calculating CRC of the byte data received. The type of the parameter was later refactored to size_t. Is there a technical superiority to using size_t in this case?
e.g.
- (uint16_t)calculateCRC16FromBytes:(unsigned char *)bytes length:(uint32_t)length;
- (uint16_t)calculateCRC16FromBytes:(unsigned char *)bytes length:(size_t)length;
size_t is commonly used for array indexing and loop counting. Programs that use other types, such as unsigned int, for array indexing may fail on, e.g. 64-bit systems when the index exceeds UINT_MAX or if it relies on 32-bit modular arithmetic.
When writing C code you should always use size_t whenever dealing with memory ranges. The int type on the other hand is basically defined as the size of the (signed) integer value that the host machine can use to most efficiently perform integer arithmetic.
The reason why size_t is encouraged is because it makes your program portable. Typically a program should not need to care how much memory is installed in the machine it is running on. But if the program logic dictates that there will be a lower limit on the number of elements then you could use a smaller index type.
The only time that using std::size_t is "better" than ::size_t is if you have not included <stddef. h> (perhaps you have #include <cstddef> instead).
According to the C specification
size_t ... is the unsigned integer type of the result of the sizeof operator
So any variable that holds the result of a sizeof
operation should be declared as size_t
. Since the length
parameter in the sample prototype could be the result of a sizeof
operation, it is appropriate to declare it as a size_t
.
e.g.
unsigned char array[2000] = { 1, 2, 3 /* ... */ };
uint16_t result = [self calculateCRC16FromBytes:array length:sizeof(array)];
You could argue that the refactoring of the length parameter was pointlessly pedantic, since you'll see no difference unless:
a) size_t is more than 32-bits
b) the sizeof the array is more than 4GB
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With