I want a datatype that can hold the value 12,000,000,000 (twelve billion) in C. Which datatype does accept this value?
I have tried long int
and long long int
for it.
I want a datatype that can hold the value 12,000,000,000 (twelve billion) in C. Which datatype does accept this value?
I have tried long int
and long long int
for it.
12,000,000,000 can certainly fit in a long long
and higher ranking types as long long
is specified to have a range at least [−(2^63 − 1) ... +(2^63 − 1)] or 9,223,372,036,854,775,807
.
long long twelve_mil = 12000000000; // No suffix needed
Lower ranking types like unsigned long
, long
, unsigned
, int
may also work. Example: C specifies that a long
has a minimum range of [-2147483647 ... +2147483647], but it may be more.
#if 12000000000 >= INT_MAX
int twelve_mil = 12000000000;
printf("%d\n", twelve_mil);
#elif 12000000000 >= LONG_MAX
long twelve_mil = 12000000000;
printf("%ld\n", twelve_mil);
#else
long long twelve_mil = 12000000000;
printf("%lld\n", twelve_mil);
#endif
We could extend this to consider even lower ranking types like unsigned short
, short
, unsigned char
signed char
and even char
. Not fruitful on many machines.
Code could consider using int64_t
. That common, yet optional type is defined in #include <stdint.h>
. Also declared there is int_least64_t
, which is always available since C99.
#include <stdint.h>
// for format specifiers
#include <inttypes.h>
int_least64_t twelve_mil = 12000000000;
printf("%" PRIdLEAST64 "\n", twelve_mil);
// or
int64_t twelve_mil = 12000000000; // Commonly available
printf("%" PRId64 "\n", twelve_mil);
Use long long int
and unsigned long long int
, or the fixed size versions int64_t
and uint64_t
located in stdint.h
. The unsigned versions has twice the max value of the signed ones. Any of them can hold your desired value.
long long int x0 = 12000000000ll;
unsigned long long int x1 = 12000000000ull;
or
#include "stdint.h"
int64_t x0 = 12000000000ll;
uint64_t x1 = 12000000000ull;
You can print the signed long long as printf("%lld", x0);
, and the unsigned long long as printf("%llu", x1);
.
You can also read more about the size and value range of numeric types at https://msdn.microsoft.com/en-us/library/s3f49ktz.aspx