Reputation:
I have a question about the following printout:
int logn = 32;
size_t count = (size_t)1<<logn; /* explicit cast required */
ssize_t count2 = (ssize_t)1<<logn;
fprintf(stderr, "count: %zu, count2: %zd\n", count, count2);
Output: count: 3119849472, count2: 4294967296
Why those two give different values?
Upvotes: 2
Views: 1872
Reputation: 145899
ssize_t
is a signed type. In implementations where ssize_t
is 32-bit (or less), this expression:
(ssize_t)1<< 32
invokes undefined behavior.
From the C Standard:
(c99, 6.5.7p4) "If E1 has a signed type and nonnegative value, and E1 x 2E2 is representable in the result type, then that is the resulting value; otherwise, the behavior is undefined."
Upvotes: 6