# Why C++?

This topic is 1423 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

So I dabble with programming, and I know some C++, C# and a little about java/javascript and HTML, and while searching around I frequently found people that say that "real game programmers" use C++ for game programming. However from what I gather even if that seems to be true, there are a lot of other programming languages, perhaps even more suitable for game programming.

So then I happened upon somewhat of a dumb but meaningful question:

Why C++?

What makes C++ the favorite/mainstream language in game programming, when other languages such as C# or javascript are easier? Is it just because C++ has been around longer? Does it offer more control over some aspects of data-storage and such? Does it simply have more support?

##### Share on other sites

I think there arent many choice there!

If we count there are only java,C++,C#,Python, Delphi... Java is only good for their embedded type, run well on many platform. But i think they are not fast as C++ and they are not very direct (in means of directX...). I worked alot with java, for server and j2me!

I'm not a master of C#, code couple of samples... They are very good for tool, windows app... that need good UI. The code is a lot easy and clear than C++ but they still work behind something (virtual machine???) like java. But I think it's very close compare to C++.

But even other lang is good for game, C++ is still superior because of the documents/samples/tutorials on the net, most of them are on C++ ! But using engines like Unity can save us a lot of time learning langs, they can export into many platforms (web,ios,pc...). Just learn the script is sometime enough (not all the time)!

##### Share on other sites

I recall one of the issues with some of the languages listed (versus C++) is you dont have tight control of garbage cleanup.  You leave it to the default and it kicks in whenever it feels like it.  You control it and now you have to do alot of work because of the standard paradigm of programmer used to leaving it to automatic OR you program as if there is no automatic and you might as well be using C++.

Performancewise anything that uses a virtual machine will be slower.  Can a JIT compiler be anywhere as good as a full blown dedicated native compiler ? and games do weird stuff the JIT might not be so great at optimizing (you can find the debates elsewhere).

I dont know if there is any need still to go to assembly code for critical chunks of code (that once was true).

Scripting languages ARE used for certain tasks and you would probably have to ask project manager what total coding line counts are used these days  between the non-scripted (C++) versus scripting like LUA, etc...

Another factor is how old are the key architects of these games?  Which languages were mature when they reached their highest coding efficiency (besides the other issues already mentioned)

Edited by wodinoneeye

##### Share on other sites

So I dabble with programming, and I know some C++, C# and a little about java/javascript and HTML, and while searching around I frequently found people that say that "real game programmers" use C++ for game programming. However from what I gather even if that seems to be true, there are a lot of other programming languages, perhaps even more suitable for game programming.

So then I happened upon somewhat of a dumb but meaningful question:

Why C++?

What makes C++ the favorite/mainstream language in game programming, when other languages such as C# or javascript are easier? Is it just because C++ has been around longer? Does it offer more control over some aspects of data-storage and such? Does it simply have more support?

The reasons we use C++ are mostly because it allows access to program nearly to the metal, and take advantage of all hardware acceleration or talk directly to the hardware.

The other reasons are legacy as we moved away from assembler towards C so in the past we made another switch from C to C++ so that we could take advantage of Object Oriented programming features of the language. All these steps were made to make programmers more efficient but not lose the access to hardware and memory management and tight control over what the code is doing as Danicco points out.

Most tripple A companies still dont use modern C++ features, generally C++ is used as C with Classes. Templates, STL containers and such are preferred to not be used. Neatly all C++ exceptions are turned off in favour of error codes in most game engines.

Edited by NightCreature83

##### Share on other sites

The simple answer is C++ saves me time. Being close to the metal is nice and all, as is control of freeing memory, but I'd drop those features in a heartbeat if there was a language with better development tools and libraries available for game programming than what exists for C++. The success of XNA+C#, until Microsoft abandoned it, demonstrates I am not alone in that attitude. C# was taking significant market share away from C++ for games development due to the strength of tools available.

##### Share on other sites

Well, theres a reason why OpenGL and DirectX are implemented in C and not C#.  If you want maximal efficiency, you have to be close to the hardware.   C is pretty much the only popular systems language left.   By systems language, I mean something that has a fairly predictable translation to machine instructions, basically something you can use to write an operating system or hardware interface.   The only thing lower are assembly (which is non-portable and very difficult to write) VHDL and Verilog, which describe hardware but not abstract it.

C++ is basically C with OO attached.  You are free to use any C function, and many do.

Which is party of the problem and why C++ is unfortunately, quite defective.  Here is a summary of the arguments http://yosefk.com/c++fqa/defective.html

To get around the deficiencies of C++, many completely omit the OO features of C++ (such as not using virtual functions, using trivial constructors/destructors and calling manual initialization and shutdown routines) At which point, you lose all the benefits of OO anyway, pn top of which you have a bunch of useless, extra code.   I like to call this "C++--"  In many cases, I also encounter what I consider to be lazy design patterns such as the singleton and factory which breaks OO methodologies (inheritance and the idea of reusable code), which again, leads one to question why we are using OO in the first place.

About the only good thing with C++ are the typesafe containers implemented in the STL.  Still, I fiind them overally verbose when using the iterators and the code just looks ugly.  Here's a gem from Ogre code I wrote a while back:


std::vector<MovableObject*>::const_iterator it = movingObjs.begin();
std::vector<MovableObject*>::const_iterator end = movingObjs.end();
while(it != end) {
MovableObject* movableObject = (*it);
// do somethign with the movable object
++it;
}

Tell me how that is better than something like


for(int n=0; n<movingObjects.size; n++) {
MovableObject* movableObject = movingObjects.objs[n];
// do something with the movable object
}


Assuming I have a proper movingObjects struct (not class) hich has the appropriate fields.
Edited by SunDog

##### Share on other sites

I know all of the languages you mention, and have done 3D graphics and much else in them all.

I say the choice is C++ is generally dogmatic.  Very few games need the small performance boost you get from that language, and perhaps more particularly, most programmers cannot use C++ in such a way as to create significantly faster code than they would in another language.

I am an experienced low level programmer, having programmed Assembly on numerous platforms and made a living doing optimization (not just ASM, but allso algorithmic).  My favorite language is C++, but I began a game a while ago in Java, simply because:

1) I wanted 'free' cross-platform support (Mac, Windows, Linux)

2) I knew that the nature of my game was such that my use of the GPU would be my bottleneck, not the code-paths on the CPU

However, someone recently introduced me to some cross-platform libraries that make writing multi-platform GL apps in C++ much easier, so I am porting my game to C++.

But this remains a personal choice.

As for your assertion that other languages are "easier," this is arguable, but the basic fact is we will all prefer what we know, and find that easier.  For example, I find Javascript an abomination of a language, even though I've done a bit of it.

In terms of performance, and assuming only moderate understanding of each language, performace will stack up as follows:

1) C++

2) C#

3) Java

4) Javascript

However, again, an experienced Javascript programmer can write a more performant game, assuming he understands the platform and GPU, than a very naive C++ programmer.

So, pick the language that suites you, and become an expert.  If you don't have a preference, choose C++ (for reasons already said).

Oh, and don't pick Javascript. LOL

##### Share on other sites
To be honest probably no difference in that case, VS's support for range-for was either missing or incomplete in VS2012 so it's not something I reach for right away.

##### Share on other sites
Mhm. While I have encountered many areas where VS2012's C++11 support is weak to non-existing ranged-for so far hasn't let me down. On the other hand I came a bit late to the VS2012 party, maybe my installer already came with an update compared to the original version.

##### Share on other sites
Yeah, it might have been in one of the updates; either way I'm on VS2013 now so it should all be good in that regard and I should start using it

##### Share on other sites

Apprently you've not heard of typedef, std::for_each and, for C++11 and onwards, lambdas...

// C++11
std::for_each(std::begin(movingObjs), std::end(movingObjs), [](MovableObject* obj)
{
// do something with obj
});

// C++14 (iirc)
std::for_each(std::begin(movingObjs), std::end(movingObjs), [](auto* obj)
{
// do something with obj
});


Also, evaluating container.size every iteration is wasteful as chances are the compiler will end up emitting code which will reload the value from memory every loop instead of register caching the value.

And for the record; inhertiance might be a part of OO but the general rule is prefer composition over inhertiance anyway.
(and last I checked Ogre was an utter utter mess anyway, which isn't the fault of C++ but of bad design. Never. Look. Again.)

My bad, the C loop above should have an int size = movingObjs.size before the first line.   I don't know how modern compilers would deal with the size lookup ... it would make sense to cache the value locally anyway, if the size is not modified in the loop I don't see a reason why this wouldn't be done.

I didn't know about for_each and auto, etc., I thnk I got this code from http://www.cplusplus.com/reference/vector/vector/begin/

Typedef would just add another line so you gain nothing unless you are doing this more than once, and you globally expose the typedef.   Which causes a fair amount of code pollution.

On the subject of Ogre, I don't think the class design is that bad, and its certainly quiet usable, once you get through the tutorials, etc.  Torchlight was written in Ogre, for instance..  The big problem is performance, and a big reason why there is a performance problem is because they used alot of OO methodologies like virtual functions.

Inhertiance should be used when it makes sense ... if the child class meets the "is-a" concept alot better than the "has-a" idea AND it also makes sense expose the entire interface of the parent class, thats when it should be done.   I can't imagine a scenario where composition makes more sense than inheritance (when inheritance makes any sense), except for reasons of performance, when you break the OO methodlogies in any case.   You also lose polymorphism when you do this, so any generic algorithms you write on the base classa ren't going to be able to be used by the child class.  In the Ogre code base for instance, you have Entity subclass from MovingObject, so in their rendering loop just iterates through all MovingObjects.  If Entity were to instead, compose MovingObject, this wouldn't work.

##### Share on other sites

To go back to your original question why C++

Like WodinOneEye, Danicco, and Night Creature all pointed out.  The most powerful feature of C++ is the ability

to reserve and release blocks of memory at will.  Most likely you will not need this power in a small indie project.

You can make a great game without ever doing this.  But...........

if you want to your game to push the machine to its absolute maximum potential, you will want to use all of its memory.

And to do this you need to control exactly what memory to allocate and what to release as your program is running

only C++ gives you that control

##### Share on other sites

To sum it up in a single phrase: C++ allows you to take tighter control of how the underlying hardware executes. To expand a bit further, when you as the programmer determines that the compiler, library, or runtime just aren't doing something at the level you need it to, you can do a great deal to push those things out of the way and take the wheel yourself.

There's a number of benchmarks floating around that pit various languages against one another to see who does what fastest, or to prove claimed performance parities. Often you see fairly literal translations from one language to another and the better ones at least do idiomatic programming in each language. Rarely, though, do you see comparisons of complex problems where the only requirement is to come up with the correct solution. If that were more common, you would see a pretty clear trend of C and C++ winning, and very often by significant factors. That's not at all to say that other languages cannot beat C or C++ at certain kinds of problems -- languages with lazy evaluation, for example, have a significant advantage at certain kinds of problems.

But, across the broad range of software and problems, C and C++ let you optimize your code by influencing how the hardware executes your code -- For example, directly controlling data packing and alignment, or having relatively unfettered access to assembly instructions through intrinsic functions, including for advanced vector instructions like SSE and AVX. There are ways to get at that from languages like C# or Java, but you're always a step or two more-removed from exercising direct control.

The ability to manage memory and object lifetimes to an incredible degree is not to be overlooked either. Its one of the significant optimization opportunities that other languages mostly don't offer. Its relative lightness compared to languages that require a heavier runtime environment also helps it span down to smaller devices -- the .NET run time might not seem too onerous a requirement to make on a PC or Xbox game, but its a different story if you're talking about the Nintendo DS, for example.

Of coarse, you pay dearly to exercise that level of control over your software, and the currency of trade is your productivity. When you need to achieve the highest levels of performance, and are willing to pay in lessened productivity, C and C++ are no-brainers. But, often time or skill are the limiting factors, and if performance is not critical, C#, Java, or those that are even slower still might offer the best balance of all factors.

On top of all that is simple momentum -- There's a legacy of C and C++ code in the games industry that's venerable, tested, and works on every relevant platform. All the popular and necessary middleware in use is C or C++, as are the the kinds of high-performance libraries used in making games -- from math, to audio, to OpenGL and DirectX. Again, there are usually ways to access these things from other languages, but there's always an extra layer or two between you and them. Its not just the relative performance of C++ to, say, C# for running game code internally that can be a burden, but also the translation and penalties associated with talking between the two.

##### Share on other sites
my 2 cents:
C++ is a powerful programming language. It's what I (and likely most people) would consider an intermediate language. This means it's in between high-level(like BASIC) and low-level(like assembly). This makes it more readily understood (by humans) while being close enough to machine language (it compiles directly to machine language with predefined asm "functions") to be fast and powerful.

That's why C++ is used most of the time.

##### Share on other sites

an intermediate language. This means it's in between high-level(like BASIC) and low-level(like assembly)

BASIC (not vb) ?:-/
What would that make python and Lua (super duper high level) :)

##### Share on other sites

I didn't rank python or Lua because I have no idea about them. I have programmed in BASIC (DOS), Assembly (both in "debug" with DOS and some ASM compiler I don't remember), and C++. No other extensive experience in other languages..... I made a game in DarkGDK with C++ and that's the only wrapper I have used......

##### Share on other sites

I think you've got some good answers already and they pretty much sum up your question for “why”.

For subject and just to add something: When size of the project grows, more control is somewhat obviously needed. This is where C++ provides but just like with any other language, there's always the flip-side, and with C++, it often requires more work because of the fact that additional control is provided.

I don't personally think there is an “ultimate language” for games or anything else for that matter, it just boils down to the question of how much control do you need for what you are doing.

##### Share on other sites

I think C++ has mature fast libraries like boost, and every device will let you build things in C++, it's also fairly good and very fast.

There are a few things about C++ that you have to do that you won't with a high level language, things such as dealing with pre compilation, pointers ect.

Also i feel like C++ can get very crazy because of the amount of language features eg marcos, templates ect.

More and more games are being written in higher level languages like JavaScript, a lot of C++ game engines let you program in a higher level language than C eg Unreal Engine lets you use UnrealScript.

Lee Penkman.

Multiplication Master

Word Smashing Word Puzzle

Edited by lee101