3

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?

1
  • It implements the post-decrement operator. Test first, modify afterwards. The final value of a is -1, not 0. Presumably the reason that 1 needs to be added again for display. Commented Sep 21, 2011 at 7:49

3 Answers 3

5

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.

Sign up to request clarification or add additional context in comments.

2 Comments

An addendum: yes, the compiler could have optimized this better, but this code is probably much easier to generate.
@Tinctorius Just looking at the code, I assumed no optimization. (With optimization, I would expect the variable a to disappear completely, with it's value being held in a register. And there are definitely more clever ways of generating the code: something like sub a, 1; jc comes to mind.)
1

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).

Comments

0

It's been a long while since I did assembler, but I would assume it's some optimisation to keep the pipelines busy / optimise register use.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.