Kartik Anand
Kartik Anand

Reputation: 4609

Printing negative int as long produces wrong result

I'm compiling the following C Code:

#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:

[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. And since both of them are signed why am I getting this output?

Upvotes: 1

Views: 99

Answers (2)

Keith Thompson
Keith Thompson

Reputation: 263467

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. But for a variadic function like printf, the compiler doesn't know what type to convert the argument to.

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). printf might grab 64 bits of data from the stack, 32 bits from your argument and another 32 bits of garbage; 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).

Use %d for an int argument, %ld for a long int argument.

Upvotes: 5

mahendiran.b
mahendiran.b

Reputation: 1323

The variable is not declared as long int . The declaration should be long int nEndIndex = -1;

Upvotes: 0

Related Questions