• Create Account

## Why C++?

Old topic!

Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

23 replies to this topic

### #1traghera  Members

422
Like
0Likes
Like

Posted 16 February 2014 - 08:36 AM

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?

### #2Alessio1989  Members

4382
Like
15Likes
Like

Posted 16 February 2014 - 08:57 AM

POPULAR

Native programming languages are preferred for critical performance code since they have a better memory management and (sometimes) less overhead than managed programming languages.

C++ is often preferred than C (in the game industry) since it is a multi-paradigm programming language.

Finally  C++ has a huge set of solid and tested tools.

Note also that AAA games are usually (always?) built using different programming languages (managed and scripting too) for different purposes.

Edited by Alessio1989, 16 February 2014 - 09:04 AM.

"Recursion is the first step towards madness." - "Skeggǫld, Skálmǫld, Skildir ro Klofnir!"
Direct3D 12 quick reference: https://github.com/alessiot89/D3D12QuickRef/

### #3greenpig83  Members

330
Like
-2Likes
Like

Posted 16 February 2014 - 09:02 AM

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)!

### #4wodinoneeye  Members

1669
Like
2Likes
Like

Posted 16 February 2014 - 10:23 AM

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, 16 February 2014 - 11:34 AM.

--------------------------------------------Ratings are Opinion, not Fact

### #5Chris_F  Members

3018
Like
8Likes
Like

Posted 16 February 2014 - 10:36 AM

POPULAR

If you were to try and re-implement something like Unreal Engine 4 in Java or C# it might become apparent why the industry uses C++ instead.

For simple indie games, I don't suppose it maters quite as much.

### #6Danicco  Members

449
Like
7Likes
Like

Posted 16 February 2014 - 11:09 AM

POPULAR

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?

Languages have "levels" which imply their "distance" from the hardware.

Programming in Assembly for example, you'd be really close to machine code, messing with how the hardware really works, so there's a lot more work to be done.

Higher level languages such as C# or Java have gone through tons of layers of code already, simplifying everything.

For example, creating a string in C# would be as simple as:

string myString = "someString";


In C, without the help of any libraries, you'd have to deal with an array of single characters:

char myString[20];
myString[0] = 's';
myString[1] = 'o';
myString[2] = 'm';
myString[3] = 'e';
//etc


(There's easier ways to initialize the variable, but the work is basically the above code)

So, the higher the language level, simpler the code management. But exactly because of this, you lose some "control" of what really happens.

For example videogames. Unlike desktop PCs, they have specific hardware set: Memory X, CPU Y.

When programming a game for a videogame you have to be aware of how much memory and CPU you have available and work with it.

In Javascript, you create variables, use them and that's it.

In C# and Java too, because they have something called "garbage collectors".

So what would happen if you keep constantly creating more and more variables and you reach the limit memory available? Crash. No more space for variables means no more variables, so expect something to crash.

In C++ and below, you can control when to delete a variable from memory, so you can make sure you'll have enough memory to continue your program.

"Garbage Collectors" in Java/C# free the memory when they detect that a variable isn't being used anymore. How do they detect it? This means there's another program running besides it checking for all variables you're creating and constantly checking them to see if they're okay to delete. This program is obviously consuming resources (CPU and Memory) as well, so that's why these languages are considered "heavier" on performance.

So, in general, the higher the language level, the heavier it is on performance because of all the things it is already doing to simplify the programmer's work.

When you want games to be as fast as possible, pushing the hardware to the limits, you don't want anything else doing (unnecessary) work for you.

Another thing about languages is that, the closer it is to the hardware (so the lower it's level), the easier it is to port to different machines.

All machines work in the same way in the lowest level possible: machine code.

The higher the level of the language, more layers it has been gone through, so more limitations it has.

For example Javascript, you must have a browser to run a javascript code (windows can work around it as well).

Or C#/Java, you must have their frameworks installed to run them (.NET and JVM), otherwise they just won't run.

So they're limited by whatever layers precede them. In comparison, an Assembly code could be run nearly anywhere - it's just a matter of how.

Taking all of these in consideration, you can figure why C/C++ is the language of choice for game programming.

It's not hard (harder than languages higher than it, obviously, but much much much easier than Assembly and lower languages), provides much control, and works nearly everywhere (where it doesn't is because the manufacturer is lazy), making your code much more portable.

But don't forget the famous "use the right tool for the job" quote. It'd be a waste of time to program in Assembly for a Windows Game just as it would be unproductive to program a game for PS3 using Javascript (not to mention the work it'd be just to have Javascript useable in the machine).

### #7NightCreature83  Members

4785
Like
0Likes
Like

Posted 16 February 2014 - 11:46 AM

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, 16 February 2014 - 11:47 AM.

Worked on titles: CMR:DiRT2, DiRT 3, DiRT: Showdown, GRID 2, theHunter, theHunter: Primal, Mad Max

### #8richardurich  Members

1187
Like
0Likes
Like

Posted 16 February 2014 - 12:20 PM

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.

### #9Azaral  Members

467
Like
1Likes
Like

Posted 16 February 2014 - 08:13 PM

### #10SunDog  Members

232
Like
-6Likes
Like

Posted 18 February 2014 - 01:45 AM

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, 18 February 2014 - 01:49 AM.

### #11phantom  Members

10766
Like
5Likes
Like

Posted 18 February 2014 - 02:24 AM

POPULAR

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.

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.)

### #12HScottH  Members

520
Like
0Likes
Like

Posted 18 February 2014 - 04:05 AM

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

### #13BitMaster  Members

8647
Like
6Likes
Like

Posted 18 February 2014 - 07:52 AM

POPULAR



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


While this is obviously valid code, why do this over
for (auto* obj : movingObjs)
{
// do something with obj
}
? Or am I missing something?

### #14phantom  Members

10766
Like
0Likes
Like

Posted 18 February 2014 - 08:45 AM

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.

### #15BitMaster  Members

8647
Like
0Likes
Like

Posted 18 February 2014 - 09:36 AM

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.

### #16phantom  Members

10766
Like
0Likes
Like

Posted 18 February 2014 - 10:15 AM

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

### #17SunDog  Members

232
Like
-1Likes
Like

Posted 19 February 2014 - 12:15 PM

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.

167
Like
0Likes
Like

Posted 20 February 2014 - 05:19 PM

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

My Projects: - www.repulse.com

### #19Ravyne  Members

14148
Like
1Likes
Like

Posted 20 February 2014 - 06:58 PM

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.

throw table_exception("(ノ ゜Д゜)ノ ︵ ┻━┻");

### #20Hawkblood  Members

954
Like
0Likes
Like

Posted 21 February 2014 - 08:30 AM

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.

Old topic!

Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.