[英]x86 Assembly Compare Arguments
我正在使用Visual Studio,並從C ++調用程序集。 我知道當您將參數傳遞給匯編時,第一個參數在ECX中,第二個參數在EDX中。 為什么不先將ECX復制到EAX就不能直接比較兩個寄存器?
C ++:
#include <iostream>
extern "C" int PassingParameters(int a, int b);
int main()
{
std::cout << "The function returned: " << PassingParameters(5, 10) << std::endl;
std::cin.get();
return 0;
}
ASM:當直接比較兩個寄存器時,這給出了錯誤的值。
.code
PassingParameters proc
cmp edx, ecx
jg ReturnEAX
mov eax, edx
ReturnEAX:
ret
PassingParameters endp
end
但是,如果我這樣寫,我將獲得正確的值,並且可以直接比較兩個寄存器,這是為什么呢?
.code
PassingParameters proc
mov eax, ecx ; copy ecx to eax.
cmp edx, ecx ; compare ecx and edx directly like above, but this gives the correct value.
jg ReturnEAX
mov eax, edx
ReturnEAX:
ret
PassingParameters endp
end
在您的第一個版本中,如果使用了jg
,則將保留eax
與進入函數時完全相同的效果(即,我們幾乎毫無頭緒)。 由於返回值通常以eax表示,因此每當執行jg
時,都會給出未定義的返回值。 換句話說,您編寫的內容大致如下:
int PassingParameters(int a, int b) {
if (a < b)
return a;
}
在這種情況下,如果a==b
或a>b
,則返回值為垃圾。
在第二個代碼序列中,您正在將一個值加載到eax中。 然后,如果未使用jg,則將另一個值加載到eax中。 無論哪種方式,返回值都將是一個輸入參數或另一個輸入參數(取決於哪個更大)。 換句話說,您擁有的大致相當於:
int PassingParameters(int a, int b) {
if (a<b)
return a;
return b;
}
PS我還要指出,您的代碼看起來像x86,根本不是64位代碼。 對於64位代碼,應使用RAX,RCX等,而不是EAX,ECX等。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.