Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Variable declarations

Status
Not open for further replies.

mubman

Programmer
Mar 10, 2004
7
GB
Hi,

A quite basic question I'm afraid. Somehow I had got it into my head that in C all variables must be declared at the start of a function block. Certainly this is convention and I would go so far as to say good practice. But from a quick test using a couple of different compilers it certainly doesn't seem that you have to do this. Was there ever a time when compilers enforced such restrictions or am I going mad?

Thanks.
 
Yes, in C, many compilers enforced this, and still do.

There are now 2 "versons" of the C Standard. The old one required declarations at the beginning of a block. The new one allows declarations anywhere.

C++ also allows declarations anywhere. If you use a C++ compiler to compile C code, it'll waive the old C restriction (since it'll really just be C++ code that strongly resembles C code).


I'd argue that, from a programming perspective, the beginning-of-block restriction is arbitrary, unncessary, and causes you do do messy, nonsensical, unintuitive (IMHO) things like declare [tt]int i;[/tt] at the top of a function where you're going to have a [tt]for[/tt] loop.

It makes more sense to me to declare variables when they will be needed, and where you have the value with which to initialize them. That's probably more relevant in C++ than in C, but it still makes some sense.
 
The only change in the past 100 years is that, with c++, you can embed declarations within your code. Otherwise it had to be either global or at the beginning of your function.

int function(void)
{
int i=1
while (i)
{
int j;
for (j=0;j<i;j++)
{
printf("i is %d j is %d",i,j);
}
char abc[10];
}
}

is now ok. Used to be that int j, and char abc had to be first.
 
History notes:
We could place declarations anywhere many years before C++ in Algol 68. Moreover, Algol 68 declarations return values!..
 
However from a stylistic and maintenance perspective, it is sometimes better (IMO) to put the majority of your declarations in the same bit of code. (ok, declarations for loop counters etc are fine), but if you know that all your declarations are at the top of a function, it makes the code easier to maintain.

K
 
I try to define all constants as close to the top of thier functions or top of the file as possible. With variables I try to keep them close to where they are used so that it is clear why they exsist.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top