C Language | Advanced Features | Assembly Language - __asm
Some compilers allow assembly instructions to be embedded in C code. Assembly language depends on the compiler, CPU, and system. This article uses the historical Microsoft Visual C++ syntax for x86 processors.
Embedding Assembly Language in C
C is a high-level language, but it is close to hardware. Assembly language maps instructions directly to machine operations and may be useful for operating-system code, hardware access, or specialized optimization.
Inline assembly is not part of standard C. Check your compiler documentation before using it. Microsoft Visual C++ historically provided the __asm keyword.
__asm Statement
__asm assembly-instruction
__asm { assembly-instruction-list }
Use a block for multiple instructions.
Code 1
#include <stdio.h>
int main() {
int x = 10, y = 20, result;
__asm {
mov eax, x
add eax, y
mov result, eax
}
printf("%d\n", result);
return 0;
}
This example illustrates the syntax used by older Microsoft Visual C++ x86 compilers. Modern compilers and 64-bit targets may require different approaches. Inline assembly reduces portability, so use it only when necessary.