views:

342

answers:

4

I'm not sure what programming in C really means: - Programming in pure C with a C compiler or - programming in C with a C++ compiler.

Apart from the differences between the C's syntax of C and the C's syntax of C++, can I safely say there are absolutely (or in very few cases) no differences between two executables in terms of performance ?

I'm thinking about this issue, because in game programming, each one of the rendering part, the game object part and the game scripting part can be programmed completely different languages, to obtain the best compromise between execution speed and easy development, and this at each one of those part.

This separation between parts can be important for me, for example, I want to make a versatile 3D adventure engine, where a community would make their own gameplay without having to mess with the engine. It would only be able to make games with a single character and several ennemies, so different game type would be covered: hack & slash, infiltration, RPG, platform, etc.

I should have put this 2 paragraphs in gamedev.stackexchange, but the first part is only about languages...

+18  A: 

There are a lot of minor nitpicks. One that strikes me as being the most obvious is that in C++, you have to cast the return value of malloc. Also structs are automatically typedefed in C++.

Always use a C compiler for C code, not C++. C++ isn't perfectly compatible with C.

A few others:

  • In C, declaring void func(); declares a function that hasn't specifed what its arguments are, whereas in C++, void func(); is equivalent to the C void func(void)', taking no arguments;
  • Prototypes are required in C++, whereas it's generally just a warning in C;
  • The type of character constants (like 'a') is int in C and char in C++;
  • The type of string literals is char [] in C and const char [] in C++;
  • Some legitimate variable names in C, like class, are reserved keywords in C++.

For all those who don't believe me and are downvoting, check out this C code:

#include <stdlib.h>

int main(int argc, char **argv) {
    int *i = malloc(sizeof(int));

    return 0;
}

Compilation under gcc is fine, but compilation under g++ gives the following errors:

test.c: In function `int main(int, char**)':
test.c:4: error: invalid conversion from `void*' to `int*'
mathepic
Also you can't use any new keywords introduced by C++ (e.g. `new`) as variable or function names if you use a C++ compiler.
sepp2k
C99 is different from C++ also.
Nyan
What? One the key things of a C++ compiler is that it is backwards compatible with C.
0A0D
@0A0D C++ gives an error on `int *foo = malloc(sizeof(int));` because you have to cast it in C++. This is an unfair downvote - please look up information before slamming people.
mathepic
@mathepic: How'd I slam you? A little touchy aren't you... I just think your statement is inaccurate. Not that C++ aren't a little more whiney about C statements.
0A0D
@0A0D If you think it is inaccurate, try compiling the `malloc` example under `gcc` and `g++`. C++ requires a cast, C doesn't.
mathepic
@0A0D: You slammed him by down voting him for something that wasn't false. C++ is most definitely not backward compatible to C. There is valid C code that is an error in C++.
JeremyP
@AOD: Even worse there is C code that compiles and has a different meaning in C++ (so no backward compatibility (unless you stick to strict subset of C)). The most obvious is sizeof('a') produces different results for C/C++
Martin York
@JeremyP: If that's a slam, then you guys need serious therapy.
0A0D
@0A0D: I think it might be better that, instead of quibbling about the precise meaning of "slam", you acknowledged that your comment about backward compatibility was incorrect.
JeremyP
@JeremyP: It's correct and the downvote stands. I'm not going to correct something that is correct. You guys need to lighten up and learn to read.
0A0D
@0A0D - What? I just proved that your reason for downvoting me was incorrect. Remove the downvote.
mathepic
@0A0D: I'm afraid you're quite wrong. You need only consult a few prominent and easily-located sources to establish that C++ is not a strict superset of C and is not fully backward compatible. There is of course the book _The C++ Programming Language_ itself, there are several FAQs, such as that by Bjarne Stroustrup himself: http://www2.research.att.com/~bs/bs_faq.html#C-is-subset and the generally thorough Parashift C++ FAQ: http://www.parashift.com/c++-faq-lite/big-picture.html#faq-6.11 -- I'm sure you can find others with a little bit of googling.
Nicholas Knight
@caf Thanks for the additional differences you edited in.
mathepic
@Nicholas: I know that. I said his statement prior was inaccurate. There are at least two downvotes and @mathepic I won't be bullied into removing a downvote. Everyone needs to lower the geek rage.
0A0D
@0A0D Name the statement that is inaccurate, then.
mathepic
A: 

I think there may be a tiny difference but often in programs the algorithms is the place where you should put most effort so whether you go C or C++ doesn't matter from the performance point of view (IMHO). C++ allows you to easier(*) abstract your model creating a more user friendly framework so even if there was a difference I wouldn't worry too much about that.

(*) i.e. better supported by the language itself.

Anders K.
A: 

Never mix this two languages, they are very different. Even in programming in "C" style you can accidentally make big mistakes by using C++ constructs.

For C software use a good C compiler that supports C99 like gcc or intel. For C++ use a good C++ compiler that does the job. Mixing them would lead to bad and dangerous code.

Example?

You see the code is in file ".cpp" and start using simple thing like std::vector that throws exceptions (for example std::vector::at... Exceptions in C code would be a disaster.

Artyom
C++ is backwards compatible with C for a reason. Nothing wrong with using memmove(...), etc for instance in a c++ program.
0A0D
@0A0d - there is no problem using C code in C++ (being accurate) but there is a bigger problem to write C++ code withing C style code.
Artyom
+4  A: 

Note: The differences between C and C++ syntax are already described on other posts... Still, something bothered me enough to prompt the following answer:

If I understood correctly, you want to have two separate parts in a program, one in C and one in C++. One supposed should have to be really fast, and the other could be slower.

In the current case (comparing C and C++ performance), there will be no visible difference if the same C code is compiled in with a C and in C++ compiler...

Of course, never underestimate how the skills of the programmer are important for the performance of a program, no matter the language.

Choosing a C compiler

Pros

  • If you're lucky (using a recent gcc, or whatever), you'll be able to use C99 new features (note that C++ has most useful parts of C99 already available, either as native to the language, or in the standard library).
  • You won't use a C++ feature by mistake, and thus, can safely bet you won't have surprises outside the K&R

Cons

  • You won't be able to use C++ features
  • Not every C compiler supports C99 (for example, Visual C++ is working hard to implement the newly C++0x standard, but did little work to implement C99)... So you could be stuck with C89 code if you work with, or target the wrong compiler.

Choosing a C++ compiler

Pros

  • You'll have access to both C and C++ libraries
  • You'll be able to use the STL and Boost
  • You'll be able to write templated code (i.e. faster and safer than their void * counterparts).
  • You'll be able to write all your code in C, excluding some minor details (C++ disallow implicit casting from void *, etc.). Fact is, the "minor details" above are considered as dangerous, which is why they generate errors or warnings on a C++ compiler.

Cons

  • If you want to export functions with the C naming convention, you'll have to use the extern "c" specifier.
  • You won't be able to implicitly cast from void * (note that this is not supposed to happen often, or even at all, in C++, so this a negligible problem when compared with potential casting errors)
  • If you write C++ code, then you'll have to learn a lot more than simple C to get it right (RAII, constructors/destructors, exceptions, etc.)

Producing C/C++ code

By C/C++, I mean code that will be correctly understood by both C and C++ compilers. While your language of choice could vary, those compatible C/C++ header will be the same (even if you code in C++ and will provide additional C++ headers for C++ users of your code)

For your C code to be compatible with others' C++ code:

  • decorate your function declarations with an extern "C" specifier, wrapped with #ifdef __cpluplus. This will make sure a C++ compiler will know those functions are exported as C functions
  • If you use them, don't let C99 features ever be seen by the C++ compiler. Some of those features will never ever be supported by any C++ compiler. Fact is, some major compilers won't even support C99 for their C compilers (see http://en.wikipedia.org/wiki/C99#Implementations)
  • Avoid using C++ keywords, or at least, don't let the C++ compiler see them (i.e. exporting a function called namespace or class or template is a bad idea)

For your C++ code to be compatible with others' C code:

  • provide alternative headers and functions wrapping C++ classes and functions. Don't punish the C++ folks by removing classes, etc., just because you want to remain compatible with C, but in the other hand, make sure the C folks will have reasonable access to your library without moving to a C++ compiler.
  • In the headers writen for the C folks, decorate your function declarations with an extern "C" specifier, wrapped with #ifdef __cpluplus. This will make sure a C++ compiler will know those functions are to be exported as C functions

Additional info

I found the following page quite interesting, as it lists the differences between C (including C99) and C++:

http://david.tribble.com/text/cdiffs.htm

Afterwords

Anyway, if C++ is considered fast and robust enough for the F-35, then it should be enough for you.

And apparently, they found it made their code writing faster, too (the code was mostly Ada, for the F-22, for example):

Unlike older generations of aircraft, such as the F-22, all software for the F-35 is written in C++ for faster code development.

Source: Wikipedia

So, if you need to choose, then choose your language because you like it, or because one as something the other has not. But not because of supposed performance difference.

paercebal
Why do you list "You'll be able to use the STL and Boost" as pro? i hate them both. I hate C++ templates and still use C++ only as C with classes and exceptions.
Lothar
@Lothar: You don't have to use them, but more options is almost never a con. And I'm sorry you don't like what are likely the greatest strengths in C++.
rlbond
Are templates really faster than void pointers? I see no reason for that.
mathepic
@Lothar: Sorry, I forgot to ask your advice when giving my own... ^_^ ... More seriously, rlbond is right. You are really missing something if you're doing C++ without templates. I suggest you to try Java or C#: A C++ without templates has no value when compared to those languages (and even then, they added generics to Java and C#, so type parametrisation must be good for something...).
paercebal
@mathepic: I was comparing code based on templates with code based on `void *`. The most obvious example was that, some years ago, qsort was slower than std::sort. The point being that templated code can usually be inlined/optimized into almost zero code, whereas void * code will be more difficult to optimize/inline. (And I'm not even speaking about code safety). And of course, the moment metaprogramming enters the arena, runtime execution becomes compile time execution, so yes, it will go faster, then.
paercebal
@Lothar: I'm now a 12 year long hard core Eiffel Programmer and C++ templates suck, i'm programming in C++ since 1994. I know how to use and write templates but i hate them and still try to avoid them and i'm lucky that my code does not really require them.
Lothar
@Lothar: Speaking as an old C fart who had to make the transition to C++ several years ago, you are not fully exploiting the power of C++ by ignoring templates and the STL. The amount of time and work you can save by leveraging these tools is *considerable*. Metaprogramming takes a while to get used to (it took me several years before I got it), but once you do you'll wonder how you did without it.
John Bode
@Lothar: Arguments like "C++ templates suck" fail to convince people, at least, on their technical viewpoint. Don't you have something more like "I don't like to put code in headers", or "I don't like the syntax", or whatever? John Bode is right: templates enable the average C++ user to use type safe containers like vectors or list, which would have been impossible (or inefficient) in a C++ without templates... The productivity increase is around a magnitude faster, if not even faster. I'd hate to see the code of your own homegrown vector-like container...
paercebal
I'm speaking about performance difference, because using classes or using struct to do something is one thing, but getting it done correctly using classes is like what stroutup said, "blowing you whole leg off". C++ frightens me, I would prefer do a lot in C and then use C++ correctly understanding why it is a real plus. And don't say it's because they use it for planes, so I should use it. Those engineers are way better than I am...
gokoon
Small note, with significant exception of MSVC, almost all modern C compilers support C99 very well (and yet much better then most modern compilers support C++03). And I worked with numerous C compilers.
Artyom
@gokoon: If you stick to C code using a C++ compiler, you should get it Ok. And it will enable you to slowly move to C++ for some features, or whatever. I never started coding in full C++. I started in C, then I added methods to my structs, then I found constructors cool, then I discovered function overloading, then... etc. etc.. You will make mistakes, but anyway, coding is doing mistakes, learning from them, and correcting them.
paercebal
@Artyom: You're right: the "significant exception of MSVC" is quite *significant*. The fact MS is focusing on its .NET platform, and still, working hard to add C++0x support to its C++ compiler is quite a contrast when you ask them about C99 support: *They just won't do it*. They feel there is no need, that the C community wanting the C99 features is not large enough to justify the resources spent on something already supported by their C++ compiler and their STL (bool, complex, vector, etc.). My guess is that MSVC will remain C89 + perhaps some trivial C99 trinkets (bool?).
paercebal
@paercebal I don't tell you - don't write in C++. Write in it, use it, it is great language, but do it in C++ way not in C. If you want to use C use good C compiler, and yes MSVC's C compiler is crap, so don't use it, there are plenty of very good C compilers for Windows. The major point is: C!=C++ and it is so significany that you need to stay with correct compiler (and BTW C99 makes C programming much easier)
Artyom
@Artyom: I was just commenting about the fact MSVC (and Borland) zero-support of C99 did cripple this same C99 standard, at least on the Windows platform. It does not mean C is dead on Windows (this would be a stupid assertion). It only means C is frozen on Windows (at least, as far as MS folks are concerned, which mean the C Windows API will remain a C89 API).
paercebal
@Artyom: Now, about the "C99 makes C programming much easier", I'm sure this must true for a C developer, but, well... In one hand, all the problems it aims to solve were solved for me a long time ago when I switched to C++, and in the other, most the problems I have solved with C++ cannot be solved in C... This to explain why C99 seems mostly ignored by the C++ folks while it was mostly praised by the C folks (Dennis Ritchie was not "ecstatic", though: See http://web.archive.org/web/20030419044211/http://www.e-businessworld.com/english/crd_language_303983.html )...
paercebal
@oaercebal, there are areas where C is useful and good. You need to understand that C and C++ as two absolutely different languages. See: http://stackoverflow.com/questions/2245196/c-urban-myths/2245362#2245362 C++ is much advanced then C but it is **not** C replacement, for many reasons. I'm very experienced both C **and** C++ developer, but I don't program in C/C++ or C+- :-)
Artyom
@Artyom: "C and C++ as two absolutely different languages"... Err, not exactly: They have the same technical roots, a very large subset of C is a subset of C++. So they have non negligible common part, which makes them "absolutely NOT different languages". A C developer can ignore C++, but a C++ developer cannot ignore C because pointers, memory allocation, if/for/switch/etc., etc. are still useful in C++... ^_^ ... The mere fact there are discussions to keep the languages compatible (see, for example, the work done on multithreading) shows the two languages have a lot in common.
paercebal