Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

while loop in assembly language

Tags:

c++

assembly

There is such code in C++:

#include <iostream>

int main(){
  int a = 4;
  while(a--){
    std::cout << (a + 1) << '\n';
  }
  return 0;
}

and corresponding code of main function in assembly code produced by g++:

.globl main
    .type   main, @function
main:
.LFB957:
    .cfi_startproc
    .cfi_personality 0x0,__gxx_personality_v0
    pushl   %ebp
    .cfi_def_cfa_offset 8
    movl    %esp, %ebp
    .cfi_offset 5, -8
    .cfi_def_cfa_register 5
    andl    $-16, %esp
    subl    $32, %esp
    movl    $4, 28(%esp)    # int a = 4;
    jmp .L2
.L3:
    movl    28(%esp), %eax     # std::cout << (a + 1) << '\n';
    addl    $1, %eax
    movl    %eax, 4(%esp)
    movl    $_ZSt4cout, (%esp)
    call    _ZNSolsEi
    movl    $10, 4(%esp)
    movl    %eax, (%esp)
    call    _ZStlsISt11char_traitsIcEERSt13basic_ostreamIcT_ES5_c
.L2:
    cmpl    $0, 28(%esp)
    setne   %al
    subl    $1, 28(%esp)    # a = a - 1
    testb   %al, %al
    jne .L3
    movl    $0, %eax
    leave
    ret
    .cfi_endproc
.LFE957:
    .size   main, .-main

What are used instructions setne and testb in following fragment for?

 .L2:
        cmpl    $0, 28(%esp)
        setne   %al
        subl    $1, 28(%esp)    # a = a - 1
        testb   %al, %al
        jne .L3

Couldn't it be just so to check in while loop whether a is not zero and jump?

like image 759
scdmb Avatar asked Jan 18 '26 14:01

scdmb


2 Answers

The while condition is formally the equivalent of:

while ( a -- != 0 )

(Omitting the comparison is a legal obfuscation.)

The compiler is generating code to compare a with 0, save the results in register al, then decrement a, and then test the saved results.

like image 197
James Kanze Avatar answered Jan 21 '26 05:01

James Kanze


Because a-- means

tmpval=a;
a=a-1;
return tmpval;

so compiler needs to save the previous value of a. In this program, the body part of while will be executed when a = 0 (after a--, so it will print 1).

like image 40
user685684 Avatar answered Jan 21 '26 04:01

user685684



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!