Thursday, April 13, 2006

Why doesn't a variable change when assigned a function result?

Consider this:
function someIntFunction: integer;
begin
  if false then
    result := 20;
end;

procedure someIntMethod;
var
  lValue: integer;
begin
  lValue := 10;
  lValue := someIntFunction;
  ShowMessage(IntToStr(lValue));
end;
What does ShowMessage show?

When this code is compiled, a compiler warning is issued for someIntFunction indicating that the result may be undefined. This is a valid warning and what is displayed will be whatever happens to be on the stack; some random value.

Now consider this:

function someStringFunction: string;
begin
  if false then
    result := '20';
end;

procedure someStringMethod;
var
  lValue: string;
begin
  lValue := '10';
  lValue := someStringFunction;
  ShowMessage(lValue);
end;
When this is compiled, there is no warning for someStringFunction. A warning should probably also be emitted, but it's not. The effect however is a bit different. In this case, the variable that the result is assigned to is unchanged. This seems to occur for any type that is reference counted: strings, dynamic arrays and interfaces.

No comments:

Post a Comment

Comments are welcome but I do moderate them. This is simply to keep things wholesome for general family viewing. By default, comments will be accepted. The few things that will cause a comment to be rejected are:

1. It is too long even though it may be well-written and make interesting points. It's supposed to be a comment, not an essay. If you have that much to say, write a blog article and backlink to me.

2. It is nasty, impolite or uses language that is unacceptable.

3. It includes a a link that has a typo or is broken in some other way.

4. It should have been sent as an e-mail since it is clearly addressed to me and does not appear to have been intended for other readers.

5. It is blatantly self-promotional. This does not mean it can't be self-promotional at all, but it should add some value over an above the marketing.