Search code examples
if-statementassemblymasmdirectivemasm32

difference between .IF and IF in assembly


what is the difference of .IF and IF directive in assembly? in document for .IF :

.IF condition1 
      statements
   [[.ELSEIF condition2 
            statements]]
   [[.ELSE
            statements]]
      .ENDIF

and for IF :

IF expression1
      ifstatements
   [[ELSEIF expression2
            elseifstatements]]
   [[ELSE
            elsestatements]]
   ENDIF

Solution

  • IF-ELSEIF-ELSE-ENDIF (without the dot) are compile-time directives. The assembler will test the conditions, and based on the results, will only include one of the sequences of statements in the resulting program. They serve the same purpose as the C preprocessor directives #if, #elif, #else, and #endif.

    .IF-.ELSEIF-.ELSE-.ENDIF (with the dot) are execution-time directives. The assembler will generate comparison and jumping instructions. They serve the same purpose as C statements in the form if (...) { ... } else if (...) { ... } else { ... }.


    Note: I'm not fluent in masm, so there might be errors in the notation of these examples.

    something EQU 1
    
    somewhere:
        mov ax, 42
        IF something == 1
        xor bx, 10
        ELSE
        mov bx, 20
        ENDIF
        add ax, bx
    

    During the preprocessing phase of compilation, the compiler will test the conditions in IF and ELSEIF statements (without the dot), and select one of the blocks of code that will end up in the program. The above code is turned into the following:

    somewhere:
        mov ax, 42
        xor bx, 10
        add ax, bx
    

    Another example:

    something EQU 1
    
    somewhere:
        mov ax, 42
        mov dx, something
        .IF dx == 1
        xor bx, 10
        .ELSE
        mov bx, 20
        .ENDIF
        add ax, bx
    

    During the preprocessing phase of compilation, the compiler will turn .IF-statements (with the dot) into assembly instructions. The above code is probably turned into the following:

    something EQU 1
    
    somewhere:
        mov ax, 42
        mov dx, 1
        cmp dx, 1
        jnz else_clause
        xor bx, 10
        jmp past_endif
    else_clause:
        mov bx, 20
    past_endif:
        add ax, bx
    

    The conditions are actually checked at execution time.