2013-03-21 Fun with C (or, @!*#%!#^&!^#$^@!%#)
(Permalink: https://mumble.net/~campbell/2013/03/21/fun-with-c)
Consider the following fragment of C code with the type T defined
to be an integer type:
uint64_t x = UINT64_C(0x0123456789abcdef);
T n = 64;
printf("%016"PRIx64"\n", (x & ~(n - 1)));
Say we're on amd64, with
sizeof(char) = 1,
sizeof(short) = 2,
sizeof(int) = 4, and
sizeof(long) = 8,
and two's-complement arithmetic -- nothing exotic or pathological
here.
Without running the code, can you guess what it prints for each of
the following definitions of the the type T?
typedef uint8_t T; typedef int8_t T;
typedef uint16_t T; typedef int16_t T;
typedef uint32_t T; typedef int32_t T;
typedef uint64_t T; typedef int64_t T;
Hint: It's not 0123456789abcdc0 in every case.
--
Copyright (c) 2006--2013, Taylor R. Campbell.
Verbatim copying and distribution of this entire article are permitted
worldwide, without royalty, in any medium, provided this notice, and
the copyright notice, are preserved.