cmp je/jg how they work in assembly

為{幸葍}努か 提交于 2021-01-20 09:34:15

问题


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

回答1:


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



回答2:


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.




回答3:


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



来源:https://stackoverflow.com/questions/12665289/cmp-je-jg-how-they-work-in-assembly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!