sprintf()处理-INF时返回正INF,此现象是Bug还是预期行为?
Is sprintf() returning "INF" for -INF a Bug or Expected Behavior?
Great question! The short answer is: this is almost certainly a bug, not intended design behavior—assuming you’re working with a C implementation that follows the C99 (or later) standard.
Let me walk through why:
- What the C Standard Requires: Starting with C99, the specification explicitly mandates that when formatting a negative infinity value with
sprintf()(using format specifiers like%f,%g, or their uppercase equivalents), the output must include a leading-sign. For example,-inf(or-INFif you use%F) is the correct output for negative infinity. A compliant implementation should never drop that negative sign. - Exceptions for Non-Standard Environments: If you’re using a very old pre-C99 compiler, or a lightweight embedded library that skips some C99 features, this might be an oversight. But even in those cases, it’s not "expected design"—it’s a missing feature or bug in that specific library, not intentional behavior.
- Quick Test to Confirm: You can verify this behavior with a simple code snippet:
If this outputs just "inf" or "INF" instead of the signed version, your#include <stdio.h> #include <math.h> int main() { char buffer[20]; sprintf(buffer, "%f", -INFINITY); printf("Output: %s\n", buffer); // Should print "-inf" (or "-INF" with %F) return 0; }sprintf()implementation isn’t following the standard.
In most modern, standard-compliant C environments (like glibc on Linux, MSVC on Windows, or Clang), this would be treated as a bug and fixed if reported.
内容的提问来源于stack exchange,提问作者mvorisek
相关产品推荐
相关产品推荐

