何时使用 size_t 与 uint32_t?我在项目中看到一个方法,它接收一个名为length(类型为uint32_t)的参数来表示要处理的字节数据的长度,该方法用于计算接收到的字节数据的CRC。参数的类型后来被重构为size_t。在这种情况下使用 size_t 是否有技术优势?
例如
- (uint16_t)calculateCRC16FromBytes:(unsigned char *)bytes length:(uint32_t)length;
- (uint16_t)calculateCRC16FromBytes:(unsigned char *)bytes length:(size_t)length;
最佳答案
根据C规范
size_t ... is the unsigned integer type of the result of the sizeof operator
所以任何保存 sizeof
结果的变量操作应声明为 size_t
.自 length
示例原型(prototype)中的参数可能是 sizeof
的结果操作,将其声明为 size_t
是合适的.
例如
unsigned char array[2000] = { 1, 2, 3 /* ... */ };
uint16_t result = [self calculateCRC16FromBytes:array length:sizeof(array)];
您可能会争辩说长度参数的重构是毫无意义的迂腐,因为您看不出有什么区别,除非:
a) size_t 大于 32 位
b) 数组大小大于4GB
关于objective-c - 何时使用 size_t 与 uint32_t?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28684322/