简体   繁体   English

为什么在printf负整数值时需要强制类型转换

[英]why do I need type casting when printf negative interger value

The following code prints a very large integer value, not -1. 下面的代码打印一个非常大的整数值,而不是-1。

int64_t num = -1
printf("%lld",num);

I need to type casting to print -1. 我需要键入强制类型才能打印-1。

printf("%lld",(int64_t) num);

Does any one know why?? 有谁知道为什么吗? Is it standard? 是标准的吗? or undefined behavior that can vary depending on the system platform? 还是不确定的行为(取决于系统平台)?

I use x86 intel processor and intel icc compiler. 我使用x86英特尔处理器和英特尔icc编译器。

I believe your code is not strictly well-defined. 我相信您的代码没有严格定义。

In order to output a int64_t type (which, if your compiler support it, must be a 2's complement 64 bit signed type), you need to first write 为了输出int64_t类型(如果您的编译器支持,则必须为2的补码64位有signed类型),您需要首先编写

#include <cinttypes>

Then use PRId64 as the format specfier: 然后使用PRId64作为格式规范:

printf("%" PRId64, num);

If you have the comparitive luxury of C++, you can use the considerably simpler std::cout which will have an appropriate overload for int64_t , assuming your platform implements that type. 如果您拥有C ++的比较优势,则可以使用相当简单的std::cout ,假设您的平台实现了该类型,则它将对int64_t具有适当的重载。

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

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