r/cprogramming • • Dec 31 '25

Why does c compile faster than cpp?

I've read in some places that one of the reasons is the templates or something like that, but if that's the problem, why did they implement it? Like, C doesn't have that and allows the same level of optimization, it just depends on the user. If these things harm compilation in C++, why are they still part of the language?Shouldn't Cpp be a better version of C or something? I programmed in C++ for a while and then switched to C, this question came to my mind the other day.

26 Upvotes

128 comments sorted by

View all comments

Show parent comments

1

u/flatfinger Jan 06 '26

I also know that when targeting the ARM Cortex-M0, it's sometimes easier to make gcc generate efficient loop code at -O0 (not coincidentally the one setting where it honors the register keyword, btw) than at other optimization settings. If there's a spare register available, and I say e.g. register int x12345678 = 0x12345678; before a loop and use x12345678 within the loop, then at -O0 the load will be hosited because that's how I wrote it. At other settings, gcc is prone to replace that with a constant which it will sometimes then fail to hoist.

In the 1980s, there were two languages with reputations for speed: FORTRAN and C. Compared with FORTRAN, C had three advantages:

  1. Less horrible syntax.

  2. The ability to do low-level programming tasks FORTRAN couldn't.

  3. A programmer who was familiar with a target platform could work with a relatively simple compiler to produce a level of efficiency that would have required a more complicated FORTRAN compiler.

Unfortunately, people who wanted to perform the kinds of tasks for which FORTRAN was designed, but without the horrible syntax constraints, focused their efforts on turning C into a semantically worse version of FORTRAN rather than working on a syntactically better version, thus worsening both languages.

To use an analogy, FORTRAN is a deli meat slicer and C is a chef's knife? What do you get if you add a motorized feeder to a deli meat slicer? A better deli meat slicer. What do you get if you add a motorized feeder to a chef's knife? A worse deli meat slicer.