nowox
nowox

Reputation: 29096

Local i variable in C?

I heard from a programmer (actually an IT teacher) that I should never write this:

void foo(bool foobar) {
   if(foobar) {
      size_t i;
      for (i = 0; i < 42; i++) {
         // Do something
      }
   } 
}

But this:

void foo(bool foobar) {
   size_t i;
   if(foobar) {
      for (i = 0; i < 42; i++) {
         // Do something
      }
   } 
}

Why?

Moreover, it seems that size_t is also bad because using a unsigned value prevent the compiler to do a good optimization.

Upvotes: 0

Views: 105

Answers (3)

Bathsheba
Bathsheba

Reputation: 234695

Old-style C (K&R) required all auto variables (in the old sense) to be declared at the beginning of the function after the part that set out the parameter types.

Newer standards (ANSI C) relax that, and modern coding conventions prefer keeping the scope of variables as tight as possible as that increases program stability.

I'd go one stage further and write (possible since C99)

for (size_t i = 0; i < 42; i++)

as then the scope of i is limited to the for loop: there's no danger it will be relied upon in error in other parts of your program.

As for using size_t as the counter, I can't see why that would constrain a compiler's optimisation strategy. In fact, I'd suspect that < could be faster on unsigned types since you don't need to handle a sign bit.

Upvotes: 1

Grzegorz Szpetkowski
Grzegorz Szpetkowski

Reputation: 37914

It is only about subjective matter of coding style. The both codes compiles equally to the same behaviour. One may preffer:

void foo(bool foobar) {
   size_t i;

   if (foobar) {
      for (i = 0; i < 42; i++) {
         // Do something
      }
   } 
}

as variable declaration is listed at the top. The second school is to declare variable closest to its usage (this code is perfectly valid in C89), so:

void foo(bool foobar) {
   if (foobar) {
      size_t i;
      for (i = 0; i < 42; i++) {
         // Do something
      }
   } 
}

can be preferred instead. Using a C99/C11 compiler it would be even to better to declare it directly in the for loop:

void foo(bool foobar) {
   if (foobar) {
      for (size_t i = 0; i < 42; i++) {
         // Do something
      }
   } 
}

Upvotes: 1

Lundin
Lundin

Reputation: 213799

That's nonsense. Always reduce the scope of variables as much as possible.

As for performance, it doesn't matter in the slightest. Since a local variable has automatic storage, the compiler will stack your variable just before it is used, no matter where the declaration appears in the source code.

That size_t would prevent the compiler from effectively optimizing your code is also nonsense.

Now what you should do, for scope and style reasons:

for (size_t i = 0; i < 42; i++) 

And if this doesn't compile, you need to upgrade to a compiler which isn't older than 15 years.

Upvotes: 18

Related Questions