1
votes

I am reviewing an old cpp program which reads data from a binary file. The code was written on Mac OS and for Mac OS. The author (who I am unable to contact) uses two variations of fread(). One with the second argument specified as sizeof(int) and one as sizeof(unsigned). Assuming that sizeof(int) == sizeof(unsinged) is there any difference in using these two methods?

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

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

specifies that the second argument is the size of bytes of each element to be read so I don't think theres should be any difference in their use-age (unless of course sizeof() is different). These two variations are mixed (seemingly randomly) throughout the file and I cannot determine why the original author would use one or the other. I just want to be sure I am not missing some tiny detail which would affect their impletmentaion.

1

1 Answers

2
votes

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

No. The sizeof operator will resolve at compile time to a value of size_t type (itself typically unsigned long or unsigned long long) that is the number of bytes in those types (normally 4 or 8).

In fact, this C++ Draft Standard states that int and unsigned int will be the same size:

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

Furthermore, the use of unsigned on its own is equivalent to unsigned int. From cppreference (I can't find it in the Draft Standard, but that site is usually reliable):

Integer types

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

(And unsigned is then listed as one of those "modifiers".)