Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

printf and %llu vs %lu on OS X [duplicate]

Possible Duplicate:
how to printf uint64_t?

Why is it that on my 64-bit Mac (I am using Clang) the uint64_t type is unsigned long long while on 64-bit Ubuntu the uint64_t type is unsigned long?

This makes it very difficult for me to get my printf calls to not give compiler warnings (or indeed even to work) under both environments.

I can try to use macros to try to choose the correct string (#define LU either %llu or %lu, and in the process uglifying the printf strings a bit) but on the Mac I've got a 64-bit word size (so _LP64 would be defined and UINTPTR_MAX != 0xffffffff) and yet it still uses long long for the 64 bit int types.

// printf macro switch (for the uint64_t's)
#if UINTPTR_MAX == 0xffffffff 
   // 32-bit
#  define LU "%llu"
#else 
   // assume 64-bit
   // special case for OS X because it is strange
   // should actually check also for __MACH__ 
#  ifdef __APPLE__
#    define LU "%llu"
#  else
#    define LU "%lu"
#  endif
#endif
like image 504
Steven Lu Avatar asked Dec 28 '12 18:12

Steven Lu


People also ask

What is the printf conversion format for double?

"%f" is the (or at least one) correct format for a double. There is no format for a float , because if you attempt to pass a float to printf , it'll be promoted to double before printf receives it1.

How do I printf a long double?

%Lf format specifier for long double %lf and %Lf plays different role in printf. So, we should use %Lf format specifier for printing a long double value.

What is the meaning of %lu in C?

%lu. Unsigned int or unsigned long.

What is %U in printf?

The %u format specifier is implemented for fetching values from the address of a variable having an unsigned decimal integer stored in the memory. It is used within the printf() function for printing the unsigned integer variable.


2 Answers

The macros are already defined for you in <cinttypes>. Try

printf("%"PRIu64, x);

Or, even better, use C++ features like

std::cout << x;

which will select the proper << operator for your variable type.

like image 68
Bo Persson Avatar answered Oct 04 '22 11:10

Bo Persson


The answer is to promote via static cast:

some_type i = 5;
printf("our value is: %llu", (unsigned long long)i);
like image 40
Grady Player Avatar answered Oct 04 '22 11:10

Grady Player