简体   繁体   English

只要输出负整数就会产生错误的结果

[英]Printing negative int as long produces wrong result

I'm compiling the following C Code: 我正在编译以下C代码:

#include <stdio.h>

int main()
{
    int nEndIndex = -1;
    printf("nEndIndex : %ld\n", nEndIndex);
    return 0;
}

I'm compiling it with GCC 4.2.4 as follows: 我正在使用GCC 4.2.4进行编译,如下所示:

[kartika@alto ~/junk]$ gcc -o test test.c
[kartika@alto ~/junk]$ ./test
nEndIndex : 4294967295
[kartika@alto ~/junk]$ gcc --version
gcc (GCC) 4.2.4
Copyright (C) 2007 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

I thought since long is bigger than an int it shouldn't be a problem to use %ld . 我认为,既然longint那么使用%ld也不是问题。 And since both of them are signed why am I getting this output? 既然两个都signed为什么我要得到这个输出?

The type of the argument (after promotion, which doesn't apply in this case) must match the type expected for the format string; 参数的类型(升级后,在这种情况下将不适用) 必须与格式字符串的预期类型匹配; otherwise the behavior is undefined. 否则,行为是不确定的。

Passing an int to a function expecting a long int is usually permitted, and causes an implicit conversion. 通常允许将int传递给期望long int的函数,这会导致隐式转换。 But for a variadic function like printf , the compiler doesn't know what type to convert the argument to. 但是对于像printf这样的可变函数,编译器不知道将参数转换为哪种类型。

The behavior is undefined, which means that quite literally anything can happen (including, if you're unlucky , the code appearing to work "correctly"). 该行为是未定义的,这意味着几乎可以发生任何事情(包括,如果您不走运 ,则该代码似乎“正确”地工作)。 In practice, let's assume that int is 32 bits and long is 64 bits (those sizes vary from system to system). 实际上,我们假设int是32位,而long是64位(这些大小随系统而异)。 printf might grab 64 bits of data from the stack, 32 bits from your argument and another 32 bits of garbage; printf可能会从堆栈中获取64位数据,从参数中获取32位数据以及另外32位垃圾信息; it will then print that data assuming that it's a long int object (because that's what you told it via the format string). 然后它将假定该数据是一个long int对象(因为这是您通过格式字符串告诉它的内容),然后打印该数据。

Use %d for an int argument, %ld for a long int argument. %d用作int参数,将%ld用作long int参数。

The variable is not declared as long int . 变量未声明为long int The declaration should be long int nEndIndex = -1; 声明应为long int nEndIndex = -1;

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

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