Input and Output operands in assembly
What you'll learn: How to safely pass variables between your C code and assembly instructions using the extended asm syntax.
Bridging the Gap
When you use basic inline assembly, the compiler is often left in the dark. It doesn't know that your assembly code just changed the value of an integer or read from a specific register. To make C and assembly talk to each other without crashing your program, we use Extended Asm.
Think of operands as a "contract." You are telling the compiler: "I am going to use this C variable as an input, and I want you to put the result into this other C variable when I'm done."
The Syntax of Communication
In C, we use a specific colon-separated format to define these inputs and outputs:
asm ("assembly code"
: "=constraint" (output_variable) /* Output operands */
: "constraint" (input_variable) /* Input operands */
);
The most common constraint is "r", which tells the compiler to pick any available general-purpose register (like EAX or EBX) to hold the value. The = sign indicates that the variable is being written to.
A Concrete Example: Adding One
Let’s say you want to use the assembly add instruction to increment a number. Instead of manually guessing which register the variable foo is in, you let C handle the mapping:
#include <stdio.h>
int main() {
int input = 10;
int output;
// We use %0 to refer to the first operand (output)
// and %1 to refer to the second (input).
asm ("addl $1, %1;"
"movl %1, %0;"
: "=r" (output) // %0: Write-only register
: "r" (input) // %1: Read-only register
);
printf("Result: %d\n", output); // Prints 11
return 0;
}
In this snippet, %0 and %1 act as placeholders. The compiler looks at your constraints, picks two registers, moves the value of input into the second register, runs your assembly, and then moves the result from the first register back into the output variable.
Why This Matters
Without defining these operands, the C compiler might try to use a register for its own purposes at the same time your assembly is using it. By declaring your inputs and outputs, you ensure the compiler stays out of the way, resulting in code that is both fast and stable.
Key takeaway
Extended assembly operands use colons and constraints (like "r") to safely map C variables to CPU registers.