Hacker News new | ask | show | jobs
by anmorgan 2485 days ago
An 8-bit microcontroller where memory is constrained and all the vendor libraries are written in C, is a good example.

Your 32-bit ARM M3/M4 cores are probably crossing that line where the memory cost of using C++ is worth it, but I would say there are still real world reasons to use C.

Though I would love to see more microcontroller vendors (or any) support C++ or Rust as part of they HAL libraries, but I think you will still find C to be perfectly viable for the low cost microcontroller application.

1 comments

If it's too small for C++, it's also too small for C. Arduino is 8 bits, and it's C++ from here to the horizon.

On ARM it is no contest, at any size.

Funny little $.10 PICcy things may not have a C++ compiler available. Then, the C compiler is better than asm, if you can fit. Otherwise, no excuse.

On Arduino, from my experience, it is easy to run into memory constraints, especially when using dynamically allocated memory like strings. And I'm taking about both the flash memory for code and the ram for data, stack, and heap.

I don't think C is always a win, but to say to never use for new projects seems overly biased. Why is your opinion about C so strong? I am curious.

Simply this: if you write C code, it produces the same instructions compiling with a C or C++ compiler.

But a C compiler restricts you to the C subset. Many of the most useful features of C++ generate no extra instructions, but make the code more maintainable. There are libraries that compile to no code except exactly what you call, optimized down to exactly the circumstances of the call, wholly inexpressible in C, that you would have to open-code directly in C, gaining no benefit from the maturity of a library.

In other words, in the absolute worst case, you write the program using only C features, and get the same program. But there is never a reason to opt for the absolute worst case when you have a better choice.

Okay, I think this reply helps frame your stance much better. You are not necessarily proposing no C ever, but saying at least start a new project with a C++ compiler / IDE and if there are reasons to use C code or rules like "don't use dynamic memory allocation", when there is a substantial reason, then that is acceptable
There is no connection between C++ and dynamic memory allocation. Most of my C++ programs allocate memory at startup, then run for weeks or months (on machines with 200+ GB of RAM) never allocating ever again. C programs routinely allocate dynamic memory, except where there is reason not to; likewise C++.

So, no, there is never a reason to confine yourself to the C subset, in a new program. "for (auto e : v)" is universally better than "for (i = 0; i != N; ++i)". Zero cost, better code.

But I would never, ever suggest using an IDE, under any circumstances, for any language.