C 中的隐式转换?
这里发生了什么:
printf("result = %d\n", 1);
printf("result = %f\n", 1);
输出:
result = 1
result = 0.000000
如果我在尝试打印这些变量之前确保它们的类型,那么它当然可以正常工作。为什么第二个 print 语句没有隐式转换为 1.00000?
What's going on here:
printf("result = %d\n", 1);
printf("result = %f\n", 1);
outputs:
result = 1
result = 0.000000
If I ensure the type of these variables before trying to print them, it works fine of course. Why is the second print statement not getting implicitly converted to 1.00000?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
在第二种情况下,格式字符串和参数类型之间不匹配 - 因此结果是未定义的行为(u)r。
In the second case you have a mismatch between your format string and the argument type - the result is therefore undefined behavio(u)r.
1 未转换为 1.0 的原因是
printf
“只是”一个具有可变数量参数的 C 函数,并且只有第一个(必需)参数具有指定类型 (const字符*
)。因此,编译器“无法”知道它应该转换“额外”参数 - 它在 printf 实际读取格式字符串并确定它应该获得浮动之前被传递。点数。现在,诚然,您的格式字符串是编译时常量,因此编译器可以从
printf
中产生特殊情况,并警告您不正确参数(正如其他人提到的,一些编译器会这样做,至少如果你要求他们这样做的话)。但在一般情况下,它无法知道任意可变参数函数使用的特定格式,并且也可以以复杂的方式构造格式字符串(例如在运行时)。总而言之,如果您希望将特定类型作为“变量”参数传递,您需要对其进行强制转换。
The reason the 1 is not converted to 1.0 is that
printf
is “just” a C function with a variable number of arguments, and only the first (required) argument has a specified type (const char *
). Therefore the compiler “cannot” know that it should be converting the “extra” argument—it gets passed beforeprintf
actually reads the format string and determines that it should get a floating point number.Now, admittedly your format string is a compile-time constant and therefore the compiler could make a special case out of
printf
and warn you about incorrect arguments (and, as others have mentioned, some compilers do this, at least if you ask them to). But in the general case it cannot know the specific formats used by arbitrary vararg functions, and it's also possible to construct the format string in complex ways (e.g. at runtime).To conclude, if you wish to pass a specific type as a “variable” argument, you need to cast it.
未定义的行为。 int 被视为 float
An undefined behavior. An int is being treated as float
简短的回答是 printf 并不是真正的 C++。 Printf 是一个 C 函数,它采用可变参数列表,并根据格式字符串中指定的类型将提供的参数应用于格式字符串。
如果您想要任何类型的实际类型检查,您应该使用流和字符串 - 良好的旧 C 风格 printf 的实际 C++ 替代品。
The short answer is that printf isn't really C++. Printf is a C function which takes a variable argument list, and applies the provided arguments to the format string basis the types specified in the format string.
If you want any sort of actual type checking, you should use streams and strings - the actual C++ alternatives to good old C-style printf.
没问题
有趣的是,如果你把'1.0'放在我想 printf 只能获取变量的地址,它无法知道它是什么,那可能 。但我本以为编译器会礼貌地警告你。
Interesting, presumably it's fine if your put '1.0'
I suppose the printf only gets the address of the variable, it has no way of knowing what it was. But I would have thought the compiler would have the decency to warn you.