Variable Declaration & Initialization :: C++

Started by
18 comments, last by kuphryn 22 years, 4 months ago
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
Advertisement
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.
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++.
- The trade-off between price and quality does not exist in Japan. Rather, the idea that high quality brings on cost reduction is widely accepted.-- Tajima & Matsubara
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
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.
I see your point.

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

Kuphryn
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++ }
<br><br> </pre>
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.
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).

char a[99999],*p=a;int main(int c,char**V){char*v=c>0?1[V]:(char*)V;if(c>=0)for(;*v&&93!=*v;){62==*v&&++p||60==*v&&--p||43==*v&&++*p||45==*v&&--*p||44==*v&&(*p=getchar())||46==*v&&putchar(*p)||91==*v&&(*p&&main(0,(char**)(--v+2))||(v=(char*)main(-1,(char**)++v)-1));++v;}else for(c=1;c;c+=(91==*v)-(93==*v),++v);return(int)v;}  /*** drpizza@battleaxe.net ***/
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++ }
<br><br> </pre> <hr height=1 noshade></SPAN></BLOCKQUOTE> <br>VC++ 6 predates the C++ standard, and it seems a little unfair to expect it to follow it.<br><br>VC++ 7 gets this particular thing correct.<br><br>However, you can force VC++ 6 to behave correctly here with a #define; something like:<br><pre>#define for if(0) {} else for </pre> <br>
char a[99999],*p=a;int main(int c,char**V){char*v=c>0?1[V]:(char*)V;if(c>=0)for(;*v&&93!=*v;){62==*v&&++p||60==*v&&--p||43==*v&&++*p||45==*v&&--*p||44==*v&&(*p=getchar())||46==*v&&putchar(*p)||91==*v&&(*p&&main(0,(char**)(--v+2))||(v=(char*)main(-1,(char**)++v)-1));++v;}else for(c=1;c;c+=(91==*v)-(93==*v),++v);return(int)v;}  /*** drpizza@battleaxe.net ***/

This topic is closed to new replies.

Advertisement