Alex Rivera | Logout

C++ constructs replacing C constructs

Asked 2008-10-22T17:48:05.280
17

After discussing with a newly arrived developer in my team, I realized that there are still, in C++, habits of using C constructs because they are supposed to be better (i.e. faster, leaner, prettier, pick your reason).

What are the examples worth sharing, showing a C constructs, compared to the similar C++ construct?

For each example, I need to read the reasons the C++ construct is as good as or even better the original C construct. The aim is to offer alternatives to some C constructs that are considered somewhat dangerous/unsafe in C++ code (C++0x valid only answers are accepted as long as clearly marked as C++0x only).

I'll post below an answer (struct inline initialization) as an example.

Note 1: Please, one answer per case. If you have multiple cases, please post multiple answers

Note 2: This is not a C question. Do not add the "C" tag to this question. This is not supposed to become a fight between C++ and C. Only the study of some constructs of the C subset of C++, and their alternative in other C++ "toolkits"

Note 3: This is not a C-bashing question. I want reasons. Boasting, bashing, and unproven comparisons will be downmodded. Mentioning C++ features without a C equivalent could be considered out of topic: I want the put side by side a C feature against a C++ feature.

Edit
Report

1 Answer

2

Following paercebal's construct using variable length arrays to get around the limitation that functions can't return constant expressions yet, here is a way to do just that, in a certain other way:

template<typename T, size_t N> char (& array_size(T(&)[N]) )[N];

I've written it in some of my other answers, but it doesn't fit anywhere better than into this thread. Now, well, here is how one could use it:

void pass(int *q) {
    int n1 = sizeof(q); // oops, size of the pointer!
    int n2 = sizeof array_size(q); // error! q is not an array!
}

int main() {
    int p[] = { 1, 2, 3, 4, 5, 6 };
    int u[sizeof array_size(p)]; // we get the size at compile time.

    pass(p);
}

Advantage over sizeof

  1. Fails for non-arrays. Will not silently work for pointers
  2. Will tell in the code that the array-size is taken.
answered 2009-01-04T20:12:52.800

Your Answer