user3029591
user3029591

Reputation:

ssize_t and size_t give different values

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

Answers (1)

ouah
ouah

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

Related Questions