Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use size_t vs uint32_t?

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;
like image 666
Boon Avatar asked Feb 23 '15 22:02

Boon


People also ask

When should size_t be used?

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 should I use size_t instead of int?

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.

Should I always use size_t?

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.

Should I use std :: size_t or size_t?

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).


1 Answers

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

like image 83
user3386109 Avatar answered Sep 26 '22 02:09

user3386109