简体   繁体   English

我们可以在g ++实现中重载sprintf吗?

[英]Can we overload sprintf in g++ implementation?

My friend was assigned to work on an existing C++ project of his company. 我的朋友被分配从事他公司现有的C ++项目。 In the source code he saw something like this: 在源代码中,他看到了以下内容:

char* tmp = "882.30";
char buff[32];
sprintf(buff, "%e", tmp);
printf("TEST: %s\n", buff);

When compiling, a warning was raised: warning: format '%e' expects type 'double', but argument 3 has type 'char*' but the output was amazing: 8.823000e+002 . 编译时,出现警告: warning: format '%e' expects type 'double', but argument 3 has type 'char*'但输出是惊人的: 8.823000e+002 He was curious. 他很好奇。 How could it be? 怎么会这样?

To clarify that he created a new small project and he used the same above code snippet and same compiler but it showed very different result: 2.647480e-314 . 为了澄清他创建了一个新的小型项目,并使用了相同的上述代码片段和相同的编译器,但结果却大不相同: 2.647480e-314

The environment: Centos 5.x, gcc 4.4.7. 环境:Centos 5.x,gcc 4.4.7。

What could be the reason here? 这可能是什么原因? The existing project has overloading function of sprintf or compilers? 现有项目是否具有sprintf或编译器的重载功能?

That's undefined behavior. 那是未定义的行为。

C99 §7.19.6.1/9 C99§7.19.6.1/ 9

If any argument is not the correct type for the corresponding conversion specification, the behavior is undefined. 如果任何参数都不是相应转换规范的正确类型,则行为未定义。

That means you are guaranteed to get unportable results/behavior. 这意味着您一定会得到无法移植的结果/行为。

You need atof to explicit convert from char * pointer to double 您需要atof才能将char *指针显式转换为double

#include <cstdio>
#include <cstdlib>

int main( void )
{
    const char* tmp = "882.30";
    char buff[32];
    sprintf(buff, "%e", atof( tmp )); 
    printf("TEST: %s\n", buff);
    return 0;
}

BTW, you can't override an existing function because that is violation to the One Definition Rule (ODR.) 顺便说一句,您不能覆盖现有功能,因为这违反了一个定义规则(ODR)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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