void vs function

Started by Retro Wolf, Tue 16/02/2016 17:08:05

Previous topic - Next topic

Retro Wolf

I've never used void before, and was curious when I saw it in another thread. My basic understanding is that it works like a function but you don't return a value. But I've written plenty of functions that don't return values.

So what's the advantages of using void? Does it matter if I stick to regular functions?
Hopefully not embarrassing myself here, sometimes I need stuff explaining in a certain way for me to get it.

Crimson Wizard

#1
AFAIK function was initially only type of function in AGS (very long ago), so I believe it was kept for backwards compatibility and traditional reasons.

In all aspects function declaration is identical to int (not void!).

Example:
Code: ags

function MyFunc()
{
    return 10;
}

int MyFunc2()
{
    return 10;
}

function game_start()
{
    Display("%d", MyFunc()); // will display "10"
    Display("%d", MyFunc2()); // will display "10"
}


About return value: AGS compiler never really checks one (we already have couple of related issues opened in the tracker). If you do not write "return" statement, the script will automatically return "0" (of corresponding type).
This is also why "function" may work in place of "void".
But that is also why any other type will work as well, although unexpectedly:
Code: ags

DynamicSprite *ThisFunctionReturnsNothing()
{
}

The code above has no "return" statement, and you may actually even use this function as if it was "void" or "function".
What it returns, in fact, is "null pointer" of type DynamicSprite.


My personal opinion is to learn using accurate return type (void, int, etc), because it lets you, and other people see what that function does, e.g., should they expect some return value at all. With just "function" you cannot tell unless there are comments or you examine the function code.

But I believe "function" will work forever for compatibility reasons, so you can as well stick to that.

Retro Wolf

Very informative, thank you CW! 

SMF spam blocked by CleanTalk