Tuesday, July 16, 2019

When True is not

Pop quiz! How can the following program …

Writeln(True);
Magic;
Writeln(True);

… output this:?

TRUE
FALSE

Simple!

In Delphi, True and False are constants. They are, however, not reserved words. That allows us to define a variable with name True and set it to False :)

var
  True: boolean = not false;

procedure Magic;
begin
  True := false;
end;

You can also define a function called True or False, if you are crazy enough.

Full program available here.

Edit

For additional fun, add this to your code. Testers will be delighted!

function False: boolean;
begin
  Result := Random(1000) = 0;
end;

Caveat

Do I have to say it? Don’t do that! True and False should stay what they are.


3 comments:

  1. procedure Magic;
    begin
    Writeln (False);
    Halt;
    end;

    ReplyDelete
  2. Moz in Oz08:10

    Ah, Pascal, home of the delightful compiler setting "writeable constants". You could also enable that and simply set "True:=False;" and ...

    ReplyDelete
  3. Anonymous19:56

    Oh, this old story, when in the depths of a huge project written in C ++ was found a line:
    #define true false; // happy debugging jerks

    ReplyDelete