咨询8051汇编中CJNE、SJMP指令里$符号的含义与用途
$符号的含义与用途解析 Hey there! Let's break down what that $ symbol does in 8051 assembly—it's actually a handy shorthand once you understand it.
At its core, $ represents the address of the current instruction being assembled. In other words, it's the value of the Program Counter (PC) at the point where the assembler encounters this symbol.
Let's walk through your examples to make this concrete:
1. SJMP $ – The Infinite Loop
This is probably the most common use of $. SJMP is a short jump instruction, and $ tells it to jump to the current instruction's address. The result? An infinite loop that stays stuck on this line forever.
You'd use this for things like:
- Halting your program after it finishes its main task (to prevent it from running off into undefined memory)
- Waiting for an interrupt trigger (since the loop will keep running until an interrupt pulls it out)
Example code snippet:
MAIN: ; Initialize port P1 as output MOV P1, #0x00 ; Blink an LED once SETB P1.0 ACALL DELAY CLR P1.0 ACALL DELAY ; Now stop here indefinitely SJMP $
2. CJNE A,#'A',$+5 – Calculating Jump Targets
CJNE is a "Compare and Jump if Not Equal" instruction, which takes a target address for the jump when the comparison fails. Here, $+5 tells the assembler to set the jump target to 5 bytes past the start of the current CJNE instruction.
Let's break the math down:
- A
CJNEinstruction in 8051 takes up 3 bytes of memory. When the CPU executes this instruction, the PC automatically increments by 3 to point to the next instruction afterCJNE. $is the starting address of theCJNEinstruction. So$+5is 5 bytes ahead of that start address. When the comparison fails, the CPU jumps directly to$+5instead of continuing to$+3.
This is way better than hardcoding a specific address because if you add or remove instructions before this line later, the assembler automatically recalculates $+5—no need to manually update jump targets.
Example code snippet:
CHECK_INPUT: ; Read a character from port P0 MOV A, P0 ; If A is not 'A', jump 5 bytes ahead CJNE A, #'A', $+5 ; If we get here, A was 'A'—turn on an LED SETB P1.0 ; Jump to the end of the check SJMP CHECK_DONE ; This is the $+5 target address ; If we get here, A was NOT 'A'—turn off the LED CLR P1.0 CHECK_DONE: ; Loop to check again SJMP CHECK_INPUT
Key Takeaways
$= current instruction's address (PC value at assembly time)- Use
SJMP $for quick, clean infinite loops - Use
$+offsetin relative jump instructions (CJNE, SJMP, JZ, etc.) to create maintainable, flexible jump targets without hardcoding addresses
内容的提问来源于stack exchange,提问作者OnurTR




