objective-c - 何时使用 size_t 与 uint32_t?

标签 objective-c c size-t uint32

何时使用 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/

相关文章:

c - c 中数学的 size_t、intptr_t 和 uintptr_t

c - 使用 size_t 变量时循环没有结束

ios - 无法点击 SKSpriteNode - 未检测到触摸 ios

iphone - commitEditingStyle 的透明背景

c - 编写一个程序,读取输入文件并识别所有重复的单词

C: 查找最长重复子串时出现 strcmp 错误

应用程序未运行时的 iOS 可达性

ios - 角标(Badge)推送增量仅适用于 xcode

c - 尽管包含 math.h,但在 C 中未定义对 pow( ) 的引用

gcc - 用于 size_t 的 printf