Flags

The values of the processor flags are shown in the top right hand corner of the CPU window. There are many jump instructions, and they usually depend on whether a flag is set (given the value 1) or clear.

Often a jump follows a compare instruction. When the operands are equal, the zero flag (ZF) is set and the commonly used JE ('Jump if Equal') instruction actually jumps when the zero flag has been set.

The carry flag (CF) is set when an operation results in the 'carry' of a bit that would no longer 'fit' into the destination operand. Program ASM_FlagDemo demonstrates that the result of 127 + 130 will not fit into the byte and confirms that the carry flag is set accordingly.

The overflow flag is set when a calculation results in the destination operand changing sign erroneously. The program demonstrates how the two's complement number held in TestShortint overflows to set the sign bit and also the overflow flag (OF) when an invalid combination of positive numbers is totalled.

program ASM_FlagDemo;
  {$APPTYPE CONSOLE}
  {$ASMMODE INTEL} //Delete this line in Delphi
uses
  SysUtils;
type
  TFlag = 0..1;
var
  TestByte : byte = 127;
  TestShortInt : ShortInt = 127;
  CarryFlag, OverflowFlag : TFlag;
begin
  asm
    ADD TestByte, 130;
    JNC @Finish; //Jump to @Finish if carry flag not set
    ADD CarryFlag, 1;
    ADD TestShortInt, 5;
    JNO @Finish; //Jump to @Finish if overflow flag not set
    ADD OverFlowFlag, 1;
    @Finish:;
  end;
  writeln('Byte: 127 + 130 gives the result ', TestByte);
  if  CarryFlag = 1 then
    writeln('Carry flag set')
  else
    writeln('Carry flag clear');
  writeln(#13#10'ShortInt: 127 + 5 gives the result ', TestShortInt);
  if  OverflowFlag = 1 then
    writeln('Overflow flag set')
  else
    writeln('Overflow flag clear');
  readln;
end.


program ASM_FlagDemoA;
  {$mode objfpc}{$H+}
  {$ASMMODE ATT}
uses
  SysUtils;
type
  TFlag = 0..1;
var
  TestByte : byte = 127;
  TestShortInt : ShortInt = 127;
  CarryFlag, OverflowFlag : TFlag;
begin
  asm
    ADD $130, TestByte
    JNC .LFinish //Jump to @Finish if carry flag not set
    ADD $1, CarryFlag
    ADD $5, TestShortInt
    JNO .LFinish //Jump to @Finish if overflow flag not set
    ADD $1, OverFlowFlag
    .LFinish:
  end;
  writeln('Byte: 127 + 130 gives the result ', TestByte);
  if  CarryFlag = 1 then
    writeln('Carry flag set')
  else
    writeln('Carry flag clear');
  writeln(#13#10'ShortInt: 127 + 5 gives the result ', TestShortInt);
  if  OverflowFlag = 1 then
    writeln('Overflow flag set')
  else
    writeln('Overflow flag clear');
  readln;
end.   
 
Programming - a skill for life!

Registers, addressing modes and flags