how dangerous is this code: String variable =0

Started by EnterTheStory (aka tolworthy), Fri 14/01/2011 19:40:44

Previous topic - Next topic

EnterTheStory (aka tolworthy)

This thread says a String parameter can have a default value, e.g.
Code: ags
function myFunction(String optional =0)
{ if(optional !=0){ runCode();}
else{return;}
}

Apparently this might, in theory, be potentially dangerous. Why? What might possibly go wrong? I'd like to use it in deeply embedded mission-critical functions, and I can't afford to take any chances.

Wyz

Well this can be safe but: you need to make sure you don't do any string operations on it when it's null.
For clarity reasons and the fact that you're infact dealing with pointers I'd change it though to:
Code: ags

function myFunction(String optional = 0)
{
    if (optional == null)
        return;
    
    runCode();
}

There is also String.IsNullOrEmpty(...) if you also want to allow empty string to also fail.
Life is like an adventure without the pixel hunts.

monkey0506

For the record, blatantly disregarding and contradicting what I said in that thread, null is not comparable to the integer-literal value of 0.

CJ has..somewhere..said that using a value of 0 is, for the time being, at least reasonably safe for this specific situation. Within the function you cannot use the integer-literal 0, and must refer to the pointer as null.

This works for all pointer types, i.e., Character:

Code: ags
import function DoSomething(Character *theCharacter=0); // the assignment of default values can only appear in the import
// note the the import does not have to be in a script header (i.e., the function does NOT have to be global), it just has to appear before the function is defined

function DoSomething(Character *theCharacter)
{
  if (theCharacter == null) theCharacter = player; // we can also use the case of null to specify an alternate default value..which we can't specify in the import
  // ...do..something?
}


So if there is a particular String value that you would like to specify as a default for your function, you can, with a reasonable amount of safety, specify a value of 0 in place of the value of null in the import for the function, and then handle the case of a null pointer within the function, replacing the parameter with the appropriate value.

I have done this..extensively..in most all of my modules since I discovered that this works. I've never had anyone complain about me doing it.

EnterTheStory (aka tolworthy)

Quote from: monkey_05_06 on Sat 15/01/2011 03:36:56you can, with a reasonable amount of safety
"reasonable amount of safety" makes me nervous :)
Quote from: monkey_05_06 on Sat 15/01/2011 03:36:56I have done this..extensively..in most all of my modules since I discovered that this works. I've never had anyone complain about me doing it.
That is reassuring. Assuming that the cause of any problems would be apparent to the user.

Thanks.

SMF spam blocked by CleanTalk