• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.

Archived

This topic is now archived and is closed to further replies.

kuphryn

Variable Declaration & Initialization :: C++

19 posts in this topic

Hi. Conventionally speaking, do you declare and initialize variables at the beginning of a function or loop or right before usage. For example: int main() { char temp; cin >> temp; cout << "1234... & " << temp; cin >> temp; cout << temp; int x; cin >> x; cout << temp << " & " << x; return 0; } The arbitrary code above depicts declaration of variables right before usage (int x). Which way is most convention is arguably better? Thanks, Kuphryn
0

Share this post


Link to post
Share on other sites
The traditional C style is to declare them all in a block, right at the beginning. Doing that is also good style because it helps keep all your variables organized. If you''re working with a large function, you might want to keep your variables closer to where they''re actually used, so you can understand your program better.

The advantage of declaring them as you need them is that it helps you have better control of how much stuff you have on the stack. For example: if you come into a function that is going to fail immediately because of an invalid parameter, you should probably wait to declare variables until after the parameter check. Otherwise, your program will enter the function, load up the stack with all your variables, then return after doing nothing. Adding all your variables to the stack is wasted effort for the computer, because they are never used.

For most applications, you''ll never need to worry about having to control your resources like this, and whatever helps you to understand your program later on is proabably the best thing to do. Myself, I develop for PocketPC, where resorces are finite. In that environment, it''s good practice not to allocate some giant array that I might not ever use until the last possible second.
0

Share this post


Link to post
Share on other sites
quote:
Original post by Anonymous Poster
The advantage of declaring them as you need them is that it helps you have better control of how much stuff you have on the stack. For example: if you come into a function that is going to fail immediately because of an invalid parameter, you should probably wait to declare variables until after the parameter check. Otherwise, your program will enter the function, load up the stack with all your variables, then return after doing nothing. Adding all your variables to the stack is wasted effort for the computer, because they are never used.


hum... all the x86 compilers I''ve used don''t work this way. A compiler could make code that does this, but it''d actually take longer on the x86. No matter where they''re declared/defined in a function, they take up the same amount stack space - and it doesn''t take any longer to allocate 128k than 4bytes; all it does it move the stack pointer by a greater offset, IIRC.

There''s a good reason to delay defintion in C++; it''s because constructors are called at the point of defintion, and can be avoided precisely as you described above.

I find code with defintions in the closest scope reasonable, are easier to follow. If I''m going to use a variable in the whole functions, I''ll declare it at the top.


for(int i=0; i


Which way is conventional, depends on whether it''s C or C++.
0

Share this post


Link to post
Share on other sites
Thanks!

I have begun to declare variable when:

1) there is something to initialize it with

int x = ...functure return, something added/subtract, etc, to other variables

2) right before its usage

int x = 3;
cout << x;

The only time I declare a variable at the top:

int x = 0;

is when it will be referenced to.

function(int &aboveX)
cout << aboveX;

So aboveX is a reference to x.

I began learning and practicing C++ about four months ago. I find something really interesting. I find that when you first learn C++ in college and reading beginner C++ books, the professor and author typically recommend declaring variables right at the top. They make it like it is imperative that we do that or the program may not work. Now, I feel that the programmer is in control of the program and that he/she can declare variables wherever is appropriate. As I mentioned, I feel it is much easier to recognize variable when the program declare them accord to the examples above.

Kuphryn
0

Share this post


Link to post
Share on other sites
1) All memory for all variables in a function are allocated at the beginning of a function in a single step, period. You cannot allocate new stack variables in the middle of a function. This is an interview-caliber question, and you should understand why this is true. If you don''t understand this, you don''t know how the C/C++ function protocol works.

2) The reason I prefer to declare variables strictly before I use them is that it''s possible to save on construction costs (not on memory allocation--see point 1).

Example:
  
void foo ()
{
SomeClassWith2MinuteCtorTime c;
if (g_notFeelingWell)
return;
c.doSomething ();
}

If I''d been smart and delayed construction of c until after I checked the g_notFeelingWell condition, my function wouldn''t have to pay the construction cost when I''m not feeling well. However, since I stuck with the C-style convention above, I have to pay that construction cost every time.
0

Share this post


Link to post
Share on other sites
I see your point.

Thanks for the insight about memory allocation at the beginning of the function. Can anyone back up that statement?

Kuphryn
0

Share this post


Link to post
Share on other sites
quote:
Original post by Magmai Kai Holmlor
I find code with defintions in the closest scope reasonable, are easier to follow. If I''m going to use a variable in the whole functions, I''ll declare it at the top.


for(int i=0; i&lt;n; i++)


Which way is conventional, depends on whether it''s C or C++.


well, C only has one option

also, visual C++ being the high quality product that it is, follows the microsoft standard, rather than the real standard.

If you have 2 loops in the same scope, both of which define the variable ''i'', the second one will be an error - that should, however, be acceptable. (only an issue if you want portable code)


for (int ii=0 ; ii&lt;10 ; ii++) { do stuff }
for (int ii=0 ; ii&lt;10 ; ii++) { error, in visual C++ }
[code]

0

Share this post


Link to post
Share on other sites
I''m not sure (since I have never done any C), but when I compile C code, all the variables have to be declared at the start (or problems arise) -- ie: for(int i = 0...) causes an error unless I use it like: int i; for(i = 0....). In C++, you can put them wherever you damn well want, but having them at the start is always good.
0

Share this post


Link to post
Share on other sites
quote:
Original post by Stoffel
1) All memory for all variables in a function are allocated at the beginning of a function in a single step, period. You cannot allocate new stack variables in the middle of a function. This is an interview-caliber question, and you should understand why this is true. If you don''t understand this, you don''t know how the C/C++ function protocol works.

We-ell....

A great many platforms offer a function alloca() (or perhaps _alloca() ), which acts like a malloc() , only it allocates memory on the stack.

Your pointer to this memory will be allocated on the stack at function invocation, and you''ll have to access your object through that pointer. But it is, strictly, created on the stack, and hence benefits from automatic deallocation (though both construction and destruction would have to be performed manually if you allocate objects on the stack in this way).

0

Share this post


Link to post
Share on other sites
quote:
Original post by Anonymous Poster
also, visual C++ being the high quality product that it is, follows the microsoft standard, rather than the real standard.
If you have 2 loops in the same scope, both of which define the variable ''i'', the second one will be an error - that should, however, be acceptable. (only an issue if you want portable code)


for (int ii=0 ; ii<10 ; ii++) { do stuff }
for (int ii=0 ; ii<10 ; ii++) { error, in visual C++ }
[code]



VC++ 6 predates the C++ standard, and it seems a little unfair to expect it to follow it.

VC++ 7 gets this particular thing correct.

However, you can force VC++ 6 to behave correctly here with a #define; something like:
#define for  if(0) {} else for 

0

Share this post


Link to post
Share on other sites
quote:
Original post by DrPizza
A great many platforms offer a function alloca() (or perhaps _alloca() ), which acts like a malloc() , only it allocates memory on the stack.


True, it is possible to allocate new stack memory, so I shouldn''t have spoken so carelessly. I was only trying to clear-up the common misconception that stack variables are given room on the stack at they time they appear in code. As you know, what really happens is that the compiler allocate memory and locations for those variables at the beginning of the function, regardless of where they are declared.

Besides, alloca is EVIL.

PS, Dr.Pizza, this:
quote:

VC++ 6 predates the C++ standard, and it seems a little unfair to expect it to follow it.


..is possibly the most level-headed thing ever said about Microsoft on this board.
0

Share this post


Link to post
Share on other sites
anon wrote "well, C only has one option"

this is not entirely true. C only requires that you declare variables at the beginning of a block--they do not have to be at the beginning of a function or loop or anything.

int main()
{
int x = 3;
printf ("x = %d\n", x);
{
int y = 2;
printf ("y = %d\n", y);
x = y;
}
printf ("x = %d\n", x);
return 0;
}

is legal C, and does not define all the function''s variables at the top of the function.

in response to the original question, people such as Stoffel & Magmai Kai Holmlor have already pointed out why "declaration before use" is preferable.

--michael

0

Share this post


Link to post
Share on other sites
i don''t know what "C" you guys are talking about, but ANSI C does NOT allow you to define variables in a function after any code. i.e.

  
void foo(void)
{
int i = 1;

i *= 1;
int j; // error.

}


is illegal.

To the vast majority of mankind, nothing is more agreeable than to escape the need for mental exertion... To most people, nothing is more troublesome than the effort of thinking.
0

Share this post


Link to post
Share on other sites
jenova:

I beleive he meant more like this...


void foo(void)
{
int i=3;
i *= 2;
printf("%d",i);
{
int j=2;
printf("*%d=%d",j,j*i);
}
}
0

Share this post


Link to post
Share on other sites
quote:
Original post by jenova
i don''t know what "C" you guys are talking about, but ANSI C does NOT allow you to define variables in a function after any code. i.e.


    
void foo(void)
{
int i = 1;

i *= 1;
int j; // error.

}


is illegal.

I''m not a C programmer, and generally dislike it (I''m a C++ kind of person), but I believe that you''re wrong on two counts.

(1) ANSI C lets you scope (and hence declare) variables to blocks. I think that a trick used by some C programmers is to do something like this:
  
void myFunction(void)
{
/* declarations */
int a, b, c;
char d, e, f;
struct MyStructType g;
/* some actual code */
a = 2; b = 3; c = a * b;
/* you can''t put any more declarations here */
/* but you can do this: */
do
{
/* declarations */
int h, i, j;
/* some actual code */

h = 4; i = 6; j = h * i;
}
while(0);
return;
}

The do... while block lets you declare additional variables, and further, restricts their scope to that block. So you can have declarations that follow code.

(2) C99 permits you to freely mix code and declarations anyway. Whilst C89 doesn''t (but I believe does permit the above), C99 is much closer to C++ in this regard.
0

Share this post


Link to post
Share on other sites
you are correct. my bad.

but i believe i read it somewhere in my "C Primer" book. i will have to check when i get home.

the code does compile under VC++ 6.0.

To the vast majority of mankind, nothing is more agreeable than to escape the need for mental exertion... To most people, nothing is more troublesome than the effort of thinking.
0

Share this post


Link to post
Share on other sites
quote:
i don''t know what "C" you guys are talking about, but ANSI C does NOT allow you to define variables in a function after any code.


According to the "C" in ANSI/ISO C Standard, ISO/IEC IS 9899, you can.
0

Share this post


Link to post
Share on other sites
AP: sweet, you must of missed my "you are correct. my bad".

To the vast majority of mankind, nothing is more agreeable than to escape the need for mental exertion... To most people, nothing is more troublesome than the effort of thinking.
0

Share this post


Link to post
Share on other sites
AP: and as "DrPizza" stated, i should have stated you cannot declare variables after code in a code block, according to C98 which my "C Primer" book is based on. okay.


your right, your right, your right. geez.

To the vast majority of mankind, nothing is more agreeable than to escape the need for mental exertion... To most people, nothing is more troublesome than the effort of thinking.
0

Share this post


Link to post
Share on other sites