user8525706
user8525706

Reputation:

Is it true that it is common for programs written in C to contain assembly code?

I have read this, saying that

For example, it is common for programs that are written primarily in C to contain portions that are in an assembly language for optimization of processor efficiency.

I have never seen a program written primarily in C that contains assembly code too, at least not directly as source code. Only, their example with the Linux kernel.

Is this statement true and if so, how could it possibly optimize processor efficiency?

Aren't C code just translated into assembly code by the compiler?

Upvotes: 4

Views: 153

Answers (2)

John Bode
John Bode

Reputation: 123558

Aren't C code just translated into assembly code by the compiler?

Yes, but...

There are situations where you may want to access a specific register or other platform-specific location, and Standard C doesn't provide good ways to do that. If you want to look at a status word or load/read a data register directly, then you often need to drop down to the assembler level.

Also, even in this age of very smart optimizing compilers, it's still possible for a human assembly programmer to write assembly code that will out-perform code generated by the compiler. If you need to wring every possible cycle out of your code, you may need to "go manual" for a couple of routines.

Upvotes: 0

Barmar
Barmar

Reputation: 782106

No, it's not true. I'd estimate that less than 1% of C programmers even know how to program in assembly, and the need to use it is very rare. It's generally only needed for very special applications, such as some parts of an OS kernel or programming embedded systems, because they need to perform machine operations that don't have corresponding C code (such as directly manipulating CPU registers). In earlier days some programmers would use it for performance-critical sections of code, but compiler optimizations have improved significantly, and CPUs have gotten faster, so this is rarely needed now. It might still be used in the built-in libraries, so that functions like strcpy() will be as fast as possible. But application programmers almost never have to resort to assembly.

Upvotes: 2

Related Questions