• Create Account

## Variable Declaration & Initialization :: 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.

19 replies to this topic

### #1kuphryn  Members

210
Like
Likes
Like

Posted 23 December 2001 - 05:22 AM

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

### #2 Anonymous Poster_Anonymous Poster_*   Guests

Likes

Posted 23 December 2001 - 08:09 AM

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.

### #3Shannon Barber  Moderators

1657
Like
Likes
Like

Posted 23 December 2001 - 08:38 PM

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

### #4kuphryn  Members

210
Like
Likes
Like

Posted 24 December 2001 - 03:28 AM

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

### #5Stoffel  Members

250
Like
Likes
Like

Posted 25 December 2001 - 06:57 PM

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.

### #6kuphryn  Members

210
Like
Likes
Like

Posted 25 December 2001 - 07:10 PM

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

Kuphryn

### #7 Anonymous Poster_Anonymous Poster_*   Guests

Likes

Posted 25 December 2001 - 07:32 PM

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]



### #8Cirian  Members

122
Like
Likes
Like

Posted 25 December 2001 - 08:20 PM

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.

### #9DrPizza  Members

160
Like
Likes
Like

Posted 26 December 2001 - 02:54 AM

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

### #10DrPizza  Members

160
Like
Likes
Like

Posted 26 December 2001 - 03:00 AM

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

### #11Stoffel  Members

250
Like
Likes
Like

Posted 26 December 2001 - 03:45 AM

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.

### #12chiuyan  Members

122
Like
Likes
Like

Posted 26 December 2001 - 09:17 AM

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

### #13jenova  Members

122
Like
Likes
Like

Posted 26 December 2001 - 09:36 AM

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.

### #14 Anonymous Poster_Anonymous Poster_*   Guests

Likes

Posted 26 December 2001 - 09:52 AM

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);   }}

### #15DrPizza  Members

160
Like
Likes
Like

Posted 26 December 2001 - 10:01 AM

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.

### #16jenova  Members

122
Like
Likes
Like

Posted 26 December 2001 - 10:56 AM

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.

### #17 Anonymous Poster_Anonymous Poster_*   Guests

Likes

Posted 26 December 2001 - 11:44 AM

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.

### #18jenova  Members

122
Like
Likes
Like

Posted 26 December 2001 - 12:19 PM

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.

### #19 Anonymous Poster_Anonymous Poster_*   Guests

Likes

Posted 26 December 2001 - 12:22 PM

### #20jenova  Members

122
Like
Likes
Like

Posted 26 December 2001 - 12:22 PM

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.