C. Keith Ray

C. Keith Ray is developing software for Sizeography and Upstart Technology. He writes code for multiple platforms and languages, including iOS® and Macintosh®.
Go to Sizeography and Upstart Technology to join our mailing lists and see more about our products. Keith's Résumé (pdf)

Thursday, August 1, 2013

C May Be Better Than C++ For Your Embedded Application

I have done some coaching of programmers writing C and C++ for embedded systems. The C programmers' target environment didn't have a heap, so C++ new/delete and associated smart pointers were out (and thus, most of C++'s standard libraries were out). But C was an improvement on assembly language for their productivity and unit testing.

The C++ programmers, though they called their target environments "embedded," really had lots of memory and full-fledged Linux or Linux-like operating systems. So they could use C++ instead of C for programming. But my experience helping them has showed me that very few programmers know how to write code that uses C++ safely (as in exception-safe code). Often their use of C++ was a hindrance to productivity, testability, and execution-efficiency.

If I could go back in time to advise those C++ embedded teams on the choice of their programming language, I'd recommend C instead of C++. It's seems like it is harder to write untestable, inefficient code in C, compared to the nightmares I've seen in C++. I've noticed that C programmers seem more pragmatic than many C++ programmers. The C++ programmers often have rules in their heads about the "right" way to code, that they have to unlearn if they want to write testable, efficient code.

If average-skilled C++ programmers could be trusted to use C++ as a "Better C" (which is how C++ used to be marketed), I would recommend that.

I'm currently programming in Objective-C with ARC. I could be blending Objective-C with C++ (just change the source file suffix to ".mm") , to take advantage of C++'s "Better C" advances in type-checking, but so far, I'm OK with the C part of Objective-C. Unit tests have found some of the issues with C's less-powerful type-checking the C++ compiler could have caught.

ARC takes Cocoa's semi-manual memory management and automates it, so I no longer have to write retain, release, or autorelease. If I didn't have ARC, I would seriously consider using C++ smart pointers to manage Objective-C memory usage. Some would view smart-pointers plus Objective-C as a worse solution than explicitly using retain and release, but manual or semi-manual memory management is very error-prone.