C Data Type Properties
A program that uses sizeof()
to show the properties of the C data types on a platform. Note you must add a link to the libray under Properties - C/C++ Build - Settings - Libraries. Add a library m
for the math library. If compiling on command line add a link to the math library with -lm
after your compile command.
datatype_sizes.c
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <math.h>
/* note: if CHAR_BIT is not defined in your limits.h un-comment the following line */
//#define CHAR_BIT 8
int main(void) {
char c;
int charBitWidth = sizeof(c) * CHAR_BIT;
printf("Data type char is %d bits wide.\n", charBitWidth);
printf(" Unsigned char min is %.0f and max is %.0f\n", -1*pow(2.0,charBitWidth-1), pow(2.0, charBitWidth-1)-1);
printf(" Signed char min is 0 and max is %.0f\n\n", pow(2.0, charBitWidth)-1);
short s;
int shortBitWidth = sizeof(s) * CHAR_BIT;
printf("Data type short is %d bits wide.\n", shortBitWidth);
printf(" Unsigned short min is %.0f and max is %.0f\n", -1*pow(2.0,shortBitWidth-1), pow(2.0, shortBitWidth-1)-1);
printf(" Signed short min is 0 and max is %.0f\n\n", pow(2.0, shortBitWidth)-1);
int i;
int intBitWidth = sizeof(i) * CHAR_BIT;
printf("Data type int is %d bits wide.\n", intBitWidth);
printf(" Unsigned int min is %.3g and max is %.3g\n", -1*pow(2.0,intBitWidth-1), pow(2.0, intBitWidth-1)-1);
printf(" Signed int min is 0 and max is %.3g\n\n", pow(2.0, intBitWidth)-1);
long l;
int longBitWidth = sizeof(l) * CHAR_BIT;
printf("Data type long is %d bits wide.\n", longBitWidth);
printf(" Unsigned long min is %.3g and max is %.3g\n", -1*pow(2.0,longBitWidth-1), pow(2.0, longBitWidth-1)-1);
printf(" Signed long min is 0 and max is %.3g\n\n", pow(2.0, longBitWidth)-1);
float f;
int floatBitWidth = sizeof(f) * CHAR_BIT;
printf("Data type float is %d bits wide.\n", floatBitWidth);
printf(" The float can have 6-7 significant digits.\n");
printf(" The float order of magnitude can vary from 10^-38 to 10^38\n\n");
double d;
int doubleBitWidth = sizeof(d) * CHAR_BIT;
printf("Data type double is %d bits wide.\n", doubleBitWidth);
printf(" The double can have 15-16 significant digits.\n");
printf(" The double order of magnitude can vary from 10^-308 to 10^307\n");
return EXIT_SUCCESS;
}