Hexadecimal floating point literals in c++

前端 未结 2 1104
无人共我
无人共我 2021-02-10 10:08

(C++) Is it possible to initialize a float variable with a hexademical float point value?

something like so:

\'0x011.1\' // wrong!

2条回答
  •  [愿得一人]
    2021-02-10 11:08

    No, C++ doesn't support that for literals, it's not part of the standard.

    A non-portable solution is to use a compiler that adds this as an extension (GCC does this).

    A portable workaround is to parse them from string literals at runtime using e.g. strtof() or strtod() for double.

    As pointed out in a comment, you can also opt to store the constants in a C file. Doing so requires that you have access to a C99 compiler though, since hex float literals is a C99-level feature. Since environments with a new C++ compiler but without a C99 compiler (read: Visual Studio) are quite common, that might not be a workable solution.

    Update: C++17 supports hexadecimal floating point literals.

提交回复
热议问题