Lazarus

Miscellaneous => Other => Topic started by: Peter H on July 18, 2019, 08:09:26 am

Title: A Fun Question
Post by: Peter H on July 18, 2019, 08:09:26 am
Hi,

Code: Pascal  [Select]
  1. program Project1;
  2.  
  3. var
  4.   a, b :boolean;
  5.  
  6. begin
  7.  
  8.   while ((a and b) <> not (not a or not b)) do
  9.       writeln('Hello World!');
  10.  
  11. end.
  12.  
  13.  


According to the theorem of de Morgan the boolean expression is always false.
It doesnt matter if  the variables are initialized or not.

So the program will do nothing.

Is there any compiler, might it be C or pascal or what else, that is clever enough to optimize this program?

 O:-)
Title: Re: A Fun Question
Post by: k1ng on July 18, 2019, 09:32:59 am
You can test it on https://godbolt.org/ ;D

gcc detects it, see
Code: C  [Select]
  1. int square(bool a, bool b) {
  2.     int x = 0;
  3.   while ((a and b) != not (not a or not b))
  4.     x = 1;
  5. }
  6.  
but seems FPC does not.
Title: Re: A Fun Question
Post by: marcov on July 18, 2019, 10:16:05 am

Is there any compiler, might it be C or pascal or what else, that is clever enough to optimize this program?

 O:-)

You can also rephrase that as "Was a compiler developer dumb enough to put time into this?".

Some might have though, mainly compilers that are used as backends (for other tools that generate C). In that case it can payout because the tool relies on C doing all the optimization, and such constructs might happen.