C Puzzle #2

· by

Contents

What is the output of the following script? Why? How can it be fixed to get the expected output?

#define __STDC_FORMAT_MACROS
#include <inttypes.h>
#include <stdio.h>

int main() {
    uint64_t testvar;

    testvar = 1<<30;
    printf("2^30 = %" PRIu64 "\n", testvar);

    testvar = 1<<31;
    printf("2^31 = %" PRIu64 "\n", testvar);

    return 0;
}

. . . . . . . . . . . . . . . . .

Answer

2^30 = 1073741824
2^31 = 18446744071562067968

Expected output

2^30 = 1073741824
2^31 = 2147483648

Explanation

1<<30 does a bitshift for int, not for uint64_t

How to fix it

Add a typecast:

#define __STDC_FORMAT_MACROS
#include <inttypes.h>
#include <stdio.h>

int main() {
    uint64_t testvar;

    testvar = 1<<30;
    printf("2^30 = %" PRIu64 "\n", testvar);

    testvar = ((uint64_t) 1)<<31;
    printf("2^31 = %" PRIu64 "\n", testvar);

    return 0;
}