title: assembly how to preserve and restore a register
body: <p>I wrote this code but my professor kept telling me to preserve and restore my registers. I thought I was by declaring a value to the empty registers.</p>
  
  <pre><code>program middleFinder;
  #include( "stdlib.hhf" ); // imports the input and output library
  static
  iDataX : int16 := 0;
  iDataY : int16 := 0;
  iDataZ : int16 := 0;
  
  
  procedure middleFindernow( x: int16; y : int16; z : int16 ); @nodisplay; @noframe; 
  // this caller must free up DH
  static
  iReturnAddress : dword;
  iMid : int16;
  iTemporary : int16;
  iRegisterValue : dword;
  
  
  begin middleFindernow;
  
  
  mov( EBX, iRegisterValue );
  // acquire parameters on the stack
  pop( iReturnAddress );
  pop(iTemporary);
  pop(iTemporary);
  mov(iTemporary, BX);
  mov( BX, z );
  pop( iTemporary ); // this is Y
  mov( iTemporary, BX );
  mov( BX, y );
  pop( iTemporary ); // this is X
  mov( iTemporary, BX );
  mov( BX, x );
  // push back the return
  push( iReturnAddress );
  push( iRegisterValue );
  
  // calculate x - y
  mov(x, DX);
  cmp(y, DX);
  je XYequal;
  cmp(y, DX);
  jl YisMax;
  cmp(y, DX);
  jg XisMax;
  
  XYequal:
  mov(y, BX);
  cmp(z, BX);
  je equal;
  jmp ExitSequence;
  
  equal:
  stdout.put("All three values are equal");
  stdout.put("AL=1");
  jmp ExitSequence;
  
  XisMax:
  // calculate x - z
  mov(0,BX);
  mov(z,BX);
  cmp(x,BX);
  jl PutXinDX;
  jg PutZinDX;
  
  
  YisMax:
  // calculate y - z
  mov(0, BX);
  mov(y, BX);
  cmp(z, BX); 
  jl PutYinDX;
  jg PutZinDX;
  
  
  PutXinDX:
  mov(x, DX);
  jmp ExitSequence;
  
  PutYinDX:
  mov(y, DX);
  jmp ExitSequence;
  
  PutZinDX:
  mov(z, DX);
  jmp ExitSequence;
  
  ExitSequence:
  // exit sequence
  // pop all preserved registers --- BX
  pop( EBX );
  ret();
  
  
  end middleFindernow;
  begin middleFinder;
  stdout.put( "gimme a X value: " );
  stdin.get( iDataX);
  stdout.put( "gimme a Y value: " );
  stdin.get( iDataY );
  stdout.put( "gimme a Z value: " );
  stdin.get( iDataZ ); 
  stdout.put( "Calling Mid number " , nl );
  mov( 0, BX );
  mov( iDataX, BX );
  push( BX );
  mov( 0, BX );
  mov( iDataY, BX );
  push( BX );
  mov( 0, BX );
  mov( iDataZ, BX );
  push( BX );
  mov( 0, BX );
  push( BX );
  call middleFindernow;
  stdout.put( "The value in the middle is " );
  stdout.puti16( DX );
  stdout.newln();
  
  end middleFinder;
  </code></pre>