sizeof() for Floating Constant in C
Last Updated :
30 Oct, 2023
In C language, we have three floating data types i.e. float, double and long double. And the exact size of each of these 3 types depends on the C compiler implementation/platform. The following program can be used to find out the size of each floating data type on your machine.
C
#include "stdio.h"
int main()
{
printf ("%d %d %d", sizeof ( float ), sizeof ( double ), sizeof ( long double ));
return 0;
}
|
But what about the size of a floating point constant (e.g. 31.4 or 2.718)? For example if we have PI macro defined as follows, what would be the sizeof(3.14). #define PI 3.14 Now if we do sizeof(PI), what will be its size? Is equal to sizeof(float) ? Or is it also compiler implementation dependent. Well, for floating constants, C standard (C11 i.e. ISO/IEC 9899:2011) has given guideline. As per C11 clause 6.4.4.2, “An unsuffixed floating constant has type double. If suffixed by the letter f or F, it has type float. If suffixed by the letter l or L, it has type long double.“ It means the type of a floating constant is same as that of double data type. So if size of a double on a machine is 8 bytes, the size of floating constant would be 8 bytes. One can find out this using the below program
C
#include "stdio.h"
#define PI 3.14
int main()
{
printf ("%d", sizeof (PI));
return 0;
}
|
As per the above mentioned C standard clause, a floating constant can be converted to float type by using f or F. Similarly, a floating constant can be converted to long double by using l or L. So it shouldn’t take much thought on guessing the output of the following:
C
#include "stdio.h"
int main()
{
printf ("%d %d", sizeof (3.14F), sizeof (3.14L));
return 0;
}
|
Please do Like/Tweet/G+1 if you find the above useful. Also, please do leave us comment for further clarification or info. We would love to help and learn 🙂
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...