3

Possible Duplicate:
What is the default value of Result in Delphi

Similar to this question, I now ask the following.

function Test:Boolean;
begin end;

Is the result value always guranteed to be false(0)? Integer values are not, so are booleans?

Community
  • 1
  • 1
pop32
  • 165
  • 3
  • 8

1 Answers1

6

No, if you don't initialise a value type function result then it's value is undefined. It could be False (0), True (1), or indeed some other integer value.

You can view a function return variable in the same light as a local variable which of course need to be initialized before use.

The moral of the tale? Always initialize your function return values.

David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
  • ok, ill wait 13 mins and accept your answer. But can you tell why if result is Boolean, it is always false? Is it my luck or what? – pop32 Mar 25 '11 at 07:03
  • 2
    Yes, it's your luck. Your function really just returns the current contents of the EAX register. Whatever code precedes your call to that function apparently sets it to zero. – Rob Kennedy Mar 25 '11 at 07:06
  • 1
    Wait — you're saying this function compiles to something other than simply `ret`? The caller will definitely read the result from EAX. Why would the function do anything with EBX, a register that has absolutely no meaning upon entry to a function? – Rob Kennedy Mar 25 '11 at 07:24
  • @Rob Ah, probably because I'm changing behaviour by passing the value to IntToStr and then on to ShowMessage. You're right as usual. – David Heffernan Mar 25 '11 at 07:25
  • @David, the analogy with local variables is not correct, because they are indeed initialized. Variables to zero, pointers to nil and strings to empty. – LU RD Mar 25 '11 at 07:47
  • 2
    @LU RD No that's not true. Only managed types are initialised. Pointers, booleans, integers, floating point types, etc., value types, are not. If you think value type local variables are initialised then you are in trouble. – David Heffernan Mar 25 '11 at 07:50
  • 1
    @LU in fact, the compiler **warns** you about uninitialized local variables you use, that's for something! – jachguate Mar 25 '11 at 07:55
  • 1
    Note: Result of managed types *MUST* be also initialized (String, interfaces, etc.)! Even if compiler does't throw a warning about it: http://qc.embarcadero.com/wc/qcmain.aspx?d=894 (Jordan Russell at 5/16/2002 7:21:10 PM) – Krystian Bigaj Mar 25 '11 at 08:23