简体   繁体   中英

Why does a negative NSInteger (long) value become garbage when sent through variadic arguments?

I've created a C function with variadic arguments (NSIntegers) like below:

NSInteger test(NSInteger arg, ...)
{
    va_list args;
    va_start(args, arg);
    NSInteger arg2 = va_arg(args, NSInteger);
    return arg + arg2;
}

On calling this function with negative second value, it somehow becomes a very large number.

test( 2,  2); // result = 4
test(-2,  2); // result = 0
test( 2, -2); // result = 4294967296

However, if I use int instead of NSInteger for the variadic argument, everything works as expected.

NSInteger test2(NSInteger arg, ...)
{
    va_list args;
    va_start(args, arg);
    int arg2 = va_arg(args, int);
    return arg + arg2;
}

Tests:

test2( 2,  2); // result = 4
test2(-2,  2); // result = 0
test2( 2, -2); // result = 0

Anything I'm probably missing here or doing something wrong? Would be great if someone can point me in the right direction here.

Thanks!

Because you're passing integer literals as the arguments, so in the case of 2 and -2 , these will be passed as int s. So you're invoking undefined behaviour by trying to read an NSInteger .

To solve this, use an explicit cast:

test(2, (NSInteger)-2);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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