请看下面在visual studio 2012中编译的代码。

#include <stdio.h>
#include <stdlib.h>
int main(void)
{
    long long end1 = 12345678908642;

    long end2 = 65537;

    printf("end1 = %lld and %u\n" , end1 , end1); // line a

    printf("end2 = %d and %ld and %u\n" , end2 , end2 , end2); // line b

    printf("end2 = %d and %ld and %lld and %u\n" , end2 , end2 , end2 , end2); // line c

    system("pause");
    return 0;
}

问题1:我想在a行中,两个数字%lld和%u显示的是相同的,而不是相同的,但是为什么在b行中,%u显示的是正确的数字?
问题2:在c行中,%lld和%u显示了错误的号码,为什么?我想它们应该和%d和%ld一样。
我很困惑。

最佳答案

转换说明符(如%u)必须与作为参数给定的相应值的类型匹配。
printf使用变量参数列表。整数提升后,实际参数将被推送到函数堆栈上,但被调用方(printf)不知道每个实际参数的偏移量;而是从格式字符串重构这些偏移量。
因此,如果您认为所有实际参数首先由调用者连接,然后由被调用者(printf)以不同的偏移量(根据与实际参数不匹配的转换说明符)读取,则可以解释您看到的奇怪行为。

关于c - 对C中%d和%ld以及%lld和%u的边界感到困惑,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31856361/

10-11 19:44