Search code examples
cobjective-cvariadic-functions

The parameter list is repeatedly passed in C function that accepts a variable number of arguments


My OC code is written like this:

NSString * CMLocalizedString(NSString *key, ... ) {
    va_list valist = NULL;
    va_start(valist, key);
    NSString* value = va_arg(valist, id);
    va_end(valist);
    
    NSLog(@"key = %@, val = %@", key, value);
    
    return key;
}

int main(int argc, const char * argv[]) {
    
    CMLocalizedString(@"SSS", nil);
    CMLocalizedString(@"BBB", @"555", @"333", nil);
    CMLocalizedString(@"AAA");
    CMLocalizedString(@"CCC");
    
    return 0;
}

But my console output is like this

key = SSS, val = (null)
key = BBB, val = 555
key = AAA, val = 555
key = CCC, val = 555

Why does va_list received duplicate values?


Solution

  • Your function CMLocalizedString expects a second argument. In the last two calls you don't pass a second argument, so you cannot expect a certain behavior from the function. That an argument from a previous call seems to be printed in place of the missing argument is just coincidence, likely due to still lying around at the same memory address.