Stats

139 Contributors: 3 Sunday, June 11, 2017
Licensed under: CC-BY-SA
Not affiliated with Stack Overflow
Rip Tutorial: riptutorial@gmail.com
Roadmap: roadmap

Inline assembly

Remarks

Inline assembly is the practice of adding assembly instructions in the middle of C source code. No ISO C standard requires support of inline assembly. Since it is not required, the syntax for inline assembly varies from compiler to compiler. Even though it is typically supported there are very few reasons to use inline assembly and many reasons not to.

Pros

  1. Performance By writing the specific assembly instructions for an operation, you can achieve better performance than the assembly code generated by the compiler. Note that these performance gains are rare. In most cases you can achieve better performance gains just by rearranging your C code so the optimizer can do its job.
  2. Hardware interface Device driver or processor startup code may need some assembly code to access the correct registers and to guarantee certain operations occur in a specific order with a specific delay between operations.

Cons

  1. Compiler Portability Syntax for inline assembly is not guaranteed to be the same from one compiler to another. If you are writing code with inline assembly that should be supported by different compilers, use preprocessor macros (#ifdef) to check which compiler is being used. Then, write a separate inline assembly section for each supported compiler.
  2. Processor Portability You can't write inline assembly for an x86 processor and expect it to work on an ARM processor. Inline assembly is intended to be written for a specific processor or processor family. If you have inline assembly that you want supported on different processors, use preprocessor macros to check which processor the code is being compiled for and to select the appropriate assembly code section.
  3. Future Performance Changes Inline assembly may be written expecting delays based upon a certain processor clock speed. If the program is compiled for a processor with a faster clock, the assembly code may not perform as expected.

Related Examples