can’t print correctly a long double in C

There’s a similar problem with MinGW under Windows. If that’s not what you’re using, this answer probably doesn’t apply.

The problem is that the compiler (GCC) and the runtime library (Microsoft’s) are implemented by different groups that happen to have different ideas about how the type long double should be represented. (gcc uses 128 bits for long double; Microsoft uses 64 bits, with the same representation as double.)

Either choice of representation is perfectly legitimate, but they’re incompatible with each other. It’s not a bug either in GCC or in Microsoft’s library, but in the way MinGW integrates them.

Your options are to use an implementation other than MinGW, to write or copy code that handles long double correctly , or to avoid calling any library functions that take arguments or return results of type long double (computations on long double shouldn’t be a problem as long as they don’t call any library functions). For example, you can convert to double and print with %g, with some loss of range and precision.

Another (probably better) workaround is to compile with -D__USE_MINGW_ANSI_STDIO, which causes MinGW to use its own implementation of printf and friends rather than relying on the Microsoft implementation.

Leave a Comment