Dear Sir,

The following is a simple program in Delphi. Could you tell me the meaning of the colour in red.

program Negatives;

{$APPTYPE CONSOLE}

uses
  SysUtils,
  ourcrt;

var
        balance, posNeg:integer;

begin
  randomize;
  writeln ('Generating your bank balance');
  writeln ('Please wait .....');
  sleep (2000);
  create a random number between 0 and 1000
  balance:=random(1000);
 randomly decide if the balance is negative
  1 for positive, 0 for negative
  posNeg:=random(2);
  if posNeg=0 then
    begin
       balance:=balance *-1;
       writeln('Can you hear that sound? Its your cheque bouncing');
       sound(200,1000);
       end
       else
         begin
           writeln ('Positive balance');
         end;
       writeln('Your balance is ', balance);
       sleep(5000);
end.

Cheers,

Dani AI

Generated

Brief answer: the red line is changing the sign of the variable so a positive balance becomes negative (and vice versa). already pointed out what it does; an idiomatic and slightly clearer way in Delphi is to use the unary minus operator instead of an explicit multiply.

Example (safe-ish approach):

if balance = Low(Integer) then
  balance64 := -Int64(balance)   // convert to larger type before negating
else
  balance := -balance;

Why this matters: -balance is easier for readers and compilers to optimize than multiplying by -1. However, negating the most-negative integer for the type (Low(Integer)) cannot be represented as a positive value in the same type, so check or use a larger integer type if that case could occur. Depending on compiler/RTL settings the result may wrap or an overflow exception may be raised, so handle that explicitly when correctness matters.

One more practical note for : the English lines you put inside your code block must be comments in Delphi. Use //, { } or (* *) for explanatory text; otherwise the IDE/compiler will flag those lines and may highlight them in red.

balance:=balance*-1;

:confused:
balance:=balance*(-1)
we want to multiply the value of balance
by negative number. :D

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.