简体   繁体   中英

What is the difference between double and long double data type in c language

I am new in programming. When I run this code

#include <stdio.h>


int main()
{
    double  i = 6.4;
    double  *ptr = &i;
    printf("The valu of ptr is %u\n",ptr);
    ptr++;
    printf("The valu of ptr is %u\n",ptr);
    ptr++;
    printf("The valu of ptr is %u\n",ptr);
    

    return 0;
}

I get this output:

The valu of ptr is 3904284976
The valu of ptr is 3904284984
The valu of ptr is 3904284992

from this it is clear that double type data needs 8 byte in my memory.

But when I run this code

#include <stdio.h>


int main()
{
    long double  i = 6.4;
    long double  *ptr = &i;
    printf("The valu of ptr is %u\n",ptr);
    ptr++;
    printf("The valu of ptr is %u\n",ptr);
    ptr++;
    printf("The valu of ptr is %u\n",ptr);
    

    return 0;
}

I get this output

The valu of ptr is 3519104768
The valu of ptr is 3519104784
The valu of ptr is 3519104800

From this it is seen that long double datatype needs 16 byte in memory.

What is the major difference between double and long double data type in c?

What is the major difference between double and long double data type in c?

Quoting from N1570 section "6.2.5 Types" this is what the C standard says:

There are three real floating types, designated as float, double, and long double.The set of values of the type float is a subset of the set of values of the type double; the set of values of the type double is a subset of the set of values of the type long double

This means that long double is a floating point type having at least the same precision as the floating point type double .

So maybe long double is the same as double . Maybe it has better precision than double . The C standard only tells us that long double can't have worse precision than double .

This is further expanded in Annex E of the standard where the "minimum requirements" for double and long double is the same.

So the difference - if any - depends on your system.

Also notice that <float.h> on your system gives you information about the three floating point types on your system. For that please refer to the "5.2.4.2.2 Characteristics of floating types <float.h>" of the standard - it's too much info to be pasted into this answer.

BTW:

Instead of using pointer values you could have printed the size, like:

printf("size of double %zu\n", sizeof(double));
printf("size of long double %zu\n", sizeof(long double));

If the sizes are different then it is very likely that long double has better precision than double .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM