Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strange "unsigned long long int" behaviour [duplicate]

Tags:

c++

c

Possible Duplicate:
How do you printf an unsigned long long int?

#include <cstdio>

int main ()
{
    unsigned long long int n;
    scanf("%llu",&n);
    printf("n: %llu\n",n);
    n /= 3;
    printf("n/3: %llu\n",n);
    return 0;
}

Whatever I put in input, I get very strange output, for example:

n: 1
n/3: 2863311531

or

n: 2
n/3: 2863311531

or

n: 1000
n/3: 2863311864

What's the reason? How should I do this correctly?

(g++ 3.4.2, Win XP)

like image 560
drevv Avatar asked May 13 '11 20:05

drevv


1 Answers

The problem is that MinGW relies on the msvcrt.dll runtime. Even though the GCC compiler supports C99-isms like long long the runtime which is processing the format string doesn't understand the "%llu" format specifier.

You'll need to use Microsoft's format specifier for 64-bit ints. I think that "%I64u" will do the trick.

If you #include <inttypes.h> you can use the macros it provides to be a little more portable:

int main ()
{
    unsigned long long int n;
    scanf("%"SCNu64, &n);
    printf("n: %"PRIu64"\n",n);
    n /= 3;
    printf("n/3: %"PRIu64"\n",n);
    return 0;
}

Note that MSVC doesn't have inttypes.h until VS 2010, so if you want to be portable to those compilers you'll need to dig up your own copy of inttypes.h or take the one from VS 2010 (which I think will work with earlier MSVC compilers, but I'm not entirely sure). Then again, to be portable to those compilers, you'd need to do something similar for the unsigned long long declaration, which would entail digging up stdint.h and using uint64_t instead of unsigned long long.

like image 85
Michael Burr Avatar answered Oct 07 '22 04:10

Michael Burr