简体   繁体   中英

Give integers a default value if they are initialized as empty

I have this (it's a Node.js addon)

void Method(const v8::FunctionCallbackInfo<v8::Value>& args) {

    int count = args[2]->ToNumber()->NumberValue();
    int priority = args[3]->ToNumber()->NumberValue();
    int priority_search_cap = args[4]->ToNumber()->NumberValue();

    cout << " count => " << count << endl;
    cout << " priority => " << priority << endl;
    cout << " priority_search_cap => " << priority_search_cap << endl;

}

what I get logged out is:

 count => -2147483648
 priority => -2147483648
 priority_search_cap => -2147483648

What I would like to do is give these variables default values in case no values are passed to properly initialize them? (Meaning, args[2], args[3], args[4] are undefined.)

How can I give these integers default values?

the Value type has a nice IsUndefined() method to check this

You could do this using a ternary expression to set value 0 in case of undefined value:

int count = args[2]->IsUndefined() ? 0 : args[2]->ToNumber()->NumberValue();
int priority = args[3]->IsUndefined() ? 0 : args[3]->ToNumber()->NumberValue();
int priority_search_cap = args[4]->IsUndefined() ? 0 : args[4]->ToNumber()->NumberValue();

check Value API here: http://bespin.cz/~ondras/html/classv8_1_1Value.html#aea287b745656baa8a12a2ae1d69744b6

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