简体   繁体   中英

When to use size_t vs uint32_t?

When to use size_t vs uint32_t? I saw aa 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?

eg

- (uint16_t)calculateCRC16FromBytes:(unsigned char *)bytes length:(uint32_t)length;

- (uint16_t)calculateCRC16FromBytes:(unsigned char *)bytes length:(size_t)length;

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 .

eg

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM