You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

cmp指令参数顺序为何重要?为何特定顺序会引发操作数类型不匹配?

Why cmpl %eax, $'A' Fails But cmpl $'A', %eax Works

Great question! This boils down to two key things: AT&T assembly syntax rules and hard constraints in the x86 instruction set that even the Intel manual might not spell out in plain English for beginners. Let’s break it down:

1. First, Let’s Clarify AT&T Syntax Operation Order

You’re using AT&T syntax (evident from the % prefix on registers and $ prefix on immediates). Unlike Intel syntax (where operands are dest, src), AT&T uses src, dest order. That means:

  • cmpl $'A', %eax translates to: Subtract the source ($'A') from the destination (%eax), then set the CPU flags based on the result. This is exactly what you want when comparing %eax against the ASCII value of 'A'.
  • cmpl %eax, $'A' on the other hand, tries to do: Subtract %eax from $'A'—which would make $'A' the destination/operand being subtracted from.

2. The x86 Instruction Set Doesn’t Allow Immediates as cmp’s "Destination"

Here’s the critical rule the Intel manual implies (via its operand format listings) but doesn’t hammer home: x86 has no instruction encoding for cmp imm, reg or cmp imm, mem.

The cmp instruction’s valid 32-bit (cmpl) operand combinations are only:

  • Register ↔ Register: cmpl %ebx, %eax (subtract ebx from eax)
  • Memory ↔ Register: cmpl %eax, (%ebx) (subtract eax from the value at ebx)
  • Register ↔ Memory: cmpl (%ebx), %eax (subtract the value at ebx from eax)
  • Register ↔ Immediate: cmpl $'A', %eax (subtract 'A' from eax)
  • Memory ↔ Immediate: cmpl $'A', (%ebx) (subtract 'A' from the value at ebx)

Notice a pattern? The operand being subtracted from (the "destination" in AT&T terms) must always be a register or memory location—never an immediate value. Immediates are just constant values; the CPU can’t treat them as a "target" operand for this instruction, even though cmp doesn’t store the subtraction result anywhere.

Your first line cmpl %eax, $'A' tries to use an immediate ($'A') as that target operand, which the assembler correctly rejects with "operand type mismatch"—there’s no valid x86 instruction for that operation.

3. Why the Intel Manual Might Seem Vague

When you checked the Intel IA-32 manual, it probably listed the cmp instruction’s operand formats like CMP r/m32, imm32 or CMP r32, r/m32. The r/m32 notation means "register or memory 32-bit"—this is explicitly telling you that the first operand (the one being subtracted from) can’t be an immediate. It’s just not phrased in plain English like "you can’t use an immediate as the first operand".


内容的提问来源于stack exchange,提问作者Jimmy Suh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 07:41:05