简体   繁体   中英

cmp je/jg how they work in assembly

I would like to understand how cmp and je/jg work in assembly. I saw few examples on google but I am still little bit confused. Below I have shown a part of assembly code that I am trying to convert to C language and the corresponding C code. Is it implemented in the right way or do I have a wrong understanding of how cmp works?

cmp    $0x3,%eax
je     A
cmp    $0x3,%eax
jg     B
cmp    $0x1,%eax
je     C


 int func(int x){


  if(x == 3)
    goto A;

  if (x >3)
    goto B;


  if(x == 1)
     goto C;

    A:
    ......

    B:
    ......

    C:
    ......

You understand correctly how cmp and je/jg work, but you have an error in your C code. This line:

if (*x == 1)

should be

if (x == 1)

Here is a pretty good summary of the x86 control flow instructions.

Also, there's no reason to repeat the cmp instruction for the same values. Once you've executed it, you can test the results multiple ways without repeating the comparison. So your assembly code should look like this:

cmp    $0x3,%eax
je     A
jg     B
cmp    $0x1,%eax
je     C

Yes, that's correct, except that in your C code you have *x in third example but x in others, that does not make sense. In your assembly code there is no correspoding code.

In C the variable type (signed/unsigned) is defined upon declaring the variable, eg. int x or unsigned int x , but in assembly the distinction between signed and unsigned variables (be they in memory or in registers) for comparisons is made by different conditional jumps:

For signed variables:

jg  ; jump if greater
jl  ; jump if less
jge ; jump if greater or equal, "jnl" is synonymous
jle ; jump if less or equal, "jng" is synonymous

For unsigned variables:

ja  ; jump if above
jb  ; jump if below
jae ; jump if above or equal, "jnb" is synonymous
jbe ; jump if below or equal, "jna" is synonymous

Intel x86 JUMP quick reference lists all conditional jumps available in x86 assembly, together with their conditions (flags' values) and their opcodes for short and long jumps.

As you may already know, the processor keeps track of the stuff that happened during last operations in a so-called flags-register. For example, there is a flag if an operation made an overflow, or the result was zero etc. The cmp mnemonic tells the processor to subtract the two registers/ register and memory content and it changes the correct flags. After that, you can jump using the jumps you have done. The processor checks the flags to see if it was equal-je, (checks the zero flag), or if it was smaller/bigger(overflow flag for unsigned and overflow and sign flag for signed numbers).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM