fRead 方法的差异

Difference in fRead methods

我正在审查一个从二进制文件读取数据的旧 cpp 程序。代码写在 Mac OS 和 Mac OS 上。作者(我无法联系到他)使用 fread() 的两种变体。一个将第二个参数指定为 sizeof(int),另一个指定为 sizeof(unsigned)。假设 sizeof(int) == sizeof(unsinged) 使用这两种方法有什么区别吗?

fread(&intArr[0], sizeof (int), 1, datafile);
fread(&intArr[0], sizeof (unsigned), 1, datafile);

http://www.cplusplus.com/reference/cstdio/fread/

指定第二个参数是要读取的每个元素的字节大小,因此我认为它们的使用期限不应该有任何差异(当然除非 sizeof() 不同)。这两种变体在整个文件中混合(看似随机),我无法确定为什么原作者会使用其中一种。我只是想确定我没有遗漏一些会影响它们实现的微小细节。

Assuming that sizeof(int) == sizeof(unsigned) is there any difference in using these two methods?

没有。 sizeof 运算符将在编译时 解析为 size_t 类型的值(本身通常为 unsigned longunsigned long long),即这些类型的字节数(通常为 4 或 8)。

事实上,this C++ Draft Standard表示intunsigned int相同尺码:

6.7.1 Fundamental Types
...
3 For each of the standard signed integer types, there exists a corresponding (but different) standard unsigned integer type: “unsigned char”, “unsigned short int”, “unsigned int”, “unsigned long int”, and “unsigned long long int”, each of which occupies the same amount of storage and has the same alignment requirements (6.6.5) as the corresponding signed integer type ...

此外,单独使用 unsigned 等同于 unsigned int。来自 cppreference(我在标准草案中找不到它,但该网站通常是可靠的):

Integer types

int - basic integer type. The keyword int may be omitted if any of the modifiers listed below are used.

(然后 unsigned 被列为 "modifiers" 之一。)