Skip to main content
GameDev.net gamedev.net
🔒 Locked

Declare variables in C++

Started by Adam4444 Jan 22, 2007 at 5:21 PM 14 replies 1.8k views
Original Post
Adam4444
Adam4444
I'm a C programmer and right now I'm trying to learn a litle C++ also (since it's the standard game programming language). In my C++ book (C++ Primer Plus) it says that it's C++ practise to declare variables just before one use them. For example:
cout << "How big are your room in m^2?\n";
int room_area;
cin >> rom_area;
And for a C programmer this looks very weird and ugly. And I just wonder which style do you use; the C-style (declare variables in the beginning of a function) or the C++ style (declare variables right before you use them)? Please motivate why. I use the C way since it feels better to have all variables in one place. And you can leave one comment for every variable at the beginning so you can watch what all variables do whitout goin down in the code.
Sneftel
Sneftel
Quote:
Original post by Adam4444
I'm a C programmer and right now I'm trying to learn a litle C++ also (since it's the standard game programming language).
In my C++ book (C++ Primer Plus) it says that it's C++ practise to declare variables just before one use them. For example:
cout << "How big are your room in m^2?\n";int room_area;cin >> rom_area;


And for a C programmer this looks very weird and ugly. And I just wonder which style do you use; the C-style (declare variables in the beginning of a function) or the C++ style (declare variables right before you use them)?

Please motivate why.

Declare your variables right before you use them. This can improve performance (because you avoid initializing variables you never use) and it definitely improves readability (because the definition is closer to where you're already looking). It can decrease memory usage (if variables are declared in an inner scope) and is often absolutely necessary (if constructor arguments are not known at the beginning of the function). It's pretty much standard.

Quote:
I use the C way since it feels better to have all variables in one place.
"Feels" better?
Quote:
And you can leave one comment for every variable at the beginning so you can watch what all variables do whitout goin down in the code.

When was the last time you cared about all the variables and none of the code?
rip-off
rip-off
It's a matter of personal preference. I tend to declare variables as near to their use as possible. I find such a style much easier to read and write.

Since C++ variable declarations can cause implicit function calls (constructors) it can be more efficient to defer declaring variables, especially if program flow constructs can cause declared objects not to be used at all. But I wouldn't argue that point too much, most variables won't have expensive constructors.
nobodynews
nobodynews
You should read up on Resource Acquisition is Initialization, or RAII. Read this wikipedia page on it and most of the articles in the external links section:
http://en.wikipedia.org/wiki/Resource_Acquisition_Is_Initialization
C++: A Dialog | C++0x Features: Part1 (lambdas, auto, static_assert) , Part 2 (rvalue references) ,
Palidine
Palidine
Quote:
Original post by Sneftel
Quote:
And you can leave one comment for every variable at the beginning so you can watch what all variables do whitout goin down in the code.

When was the last time you cared about all the variables and none of the code?


And when was the last time you needed a comment to figure out what a variable did? If that's the case you need a new naming convention. =)

-me

OrangyTang
OrangyTang
Quote:
Original post by rip-off
It's a matter of personal preference.

Nonsense. Variables should always be declared in the smallest possible scope that makes sense. As well as all the things Sneftel mentioned, keeping the scope small means you only have to think about the variables which are currently relevent, and not just the ones needed later.

Keeping the scope small can often make the code more robust (eg. within a loop rather than outside).
Crypter
Crypter
Quote:

I use the C way since it feels better to have all variables in one place.

I agree with you on the fact that C varables are more structured (ie, all varables declared in same place), However I prefer the C++ method for all of the previous reasons mentioned. Primarily..

-Improves performance

-Increases readibility

-Follows functional cohesion within a logical set of instructions. ie, varables placed only where they are needed, and close to the code that uses them
TheUnbeliever
TheUnbeliever
There is a reason that C99 removed the need to have the variables declared at the start of the function...
[TheUnbeliever]
ChristianPena
ChristianPena
One other point which may have been mentioned is that when you declare your variables closer to where they are used, you will find it easier to refactor the portions of code using those variables since you will not have to hunt down the variable declaration at the beginning of the code block.
Adam4444
Adam4444
Thanks for your reflections. It seems like it's best to do it in the C++/C99 way... It will be hard to switch for me since I'm used with the other way. But I only do it because it's faster, otherwise I would never ever declare variables in such ugly way. :P
mikeman
mikeman
Quote:
Original post by Adam4444
But I only do it because it's faster, otherwise I would never ever declare variables in such ugly way. :P


I have come to the conclusion that,when dealing with C++ beginners, we shouldn't bother explaining to them the advantages of the "proper way" as far as design/encapsulation/refactoring/whatever goes. We should just tell them it's "faster". Speed does seem to impress them more than anything else.[smile]

Btw, it's not "ugly". It's just different. I came from Delphi to C++, so I thought to too, but now I actually find weird the Pascal way(declaring all variables in the start). It will grow on you.
MaulingMonkey
MaulingMonkey
Quote:
Original post by Adam4444
I use the C way since it feels better to have all variables in one place. And you can leave one comment for every variable at the beginning so you can watch what all variables do whitout goin down in the code.


I usually use the C++ way, as I usually am directly initializing the variable with a constructor. When I don't, I often declare the variable at the start of the code "Paragraph". I'd write, for example:

void ask_size() {    int room_width_1;    std::cout << "How wide is your room (in meters)?" << std::endl;    std::cin >> room_width_1;    int room_width_2;    std::cout << "How wide is your room in the other dimension?" << std::endl;    std::cin >> room_width_2;    int room_area = room_width_1 * room_width_2;    std::cout << "And your result is..." << std::endl;    std::cout << "Room area: " << room_area << std::endl;}


The advantage of this style is that I cannot accidentally use a variable before it's "initialized".

My IDE automatically displays the values of all local variables without the need to roll over them, so that's a non-issue for me.
skillfreak
skillfreak
I don't want to beat a dead horse, but the book Effective C++ treats this issue in Item 26: Postpone variable definitions as long as possible. It follows the advice of those above.

There is also a special case for looping (construction vs. assignment) that I didn't see anyone mention (rapid skim), where this advice (variable postponement) is not sound. Refer book - a great resource.
Zahlman
Zahlman
Quote:
Original post by Adam4444
it feels better to have all variables in one place.


If the variables are related to each other in some way (describe parts of a whole), then that's what structs are for. You *have* been using those in C, yes? Well, in C++ you get several advantages automatically :)

// hooray C++!struct Color { // no need for the 'typedef struct' idiom. 'Color' names a type,// and we'll never need to write 'struct Color' anywhere except right here// (or in a forward declaration).  int red;  int green;  int blue;  // We can give constructors to constructors exactly as we do to classes.  // In fact, C++ structs *are* classes, just with protection defaulting to  // public rather than private. The intent is to allow C struct declarations to  // compile as-is, while having your code actually declare a class.  Color(int r, int g, int b) : red(r), green(g), blue(b) {}};// A struct is a data type; we can accept and return them with no problems.Color combine(const Color& a, const Color& b) {  // In particular, we can copy them with no problems:  Color x = a;  Color y(a); // equivalent to the above, using constructor syntax.  // And assign them with no problems:  x = b; // definitely can't do this in C, even in modern versions of the standard.  return Color((a.r + b.r)/2, (a.g + b.g)/2, (a.b + b.b)/2);  // and just try doing THAT in C ;)}


In short, you can get your feet wet with classes and structs in C++ quite easily, making *real data types* from the get-go, and learning how to protect them properly later. It just keeps getting better. :)
Captain P
Captain P
Quote:
Original post by mikeman
I have come to the conclusion that,when dealing with C++ beginners, we shouldn't bother explaining to them the advantages of the "proper way" as far as design/encapsulation/refactoring/whatever goes. We should just tell them it's "faster". Speed does seem to impress them more than anything else.[smile]


That just made my day! :D

Anyway, I'm currently working with C, while I have a C++ background. This particular subject was quite confusing at first - I wasn't aware of this aspect of C. However, now I simply add some more scope blocks here and there, to make the code easier to read and to allow variable declaration when I need them, or at least pretty close to when I need them.
Striken
Striken
It can be compiler dependent - some people will prefer to whack everything at the top as certainly with the Gamecube there have been problems when defining the samed local variable twice within a function, regardless of the scope, it hasn't forgotten about it and throws a compiler error, that way it's much easier to put everything at the top, so you can see EXACTLY what's declared in your function.

So on that point alone I disagree with the "readability" agrument. Everything together at the top makes it clearly visible for every programmer working on the project to see what is called what, so they can avoid problems like this. Certainly as well putting everything in size order at the top of the function can help any data alignment, again, compiler dependent. You might also find the compiler will initialize every local function variable initially anyway.

I'm just playing devil's advocate really - the "C++" way is by FAR the better option, but it's best to know all sides of this argument :), but I do agree with you, it is "messier" - and a very good code design philosophy that I swear by is that if it looks good and tidy, it's practical and will help other people trying to read your code understand it faster.
Teach a programmer an answer, he can code for a day. Show a programmer the documentation, he can code for a lifetime.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.