3

I wonder, does it make a difference where I declare local variables in a function? So for example this:

 #include <stdio.h>
 #include <unistd.h>

int main(int argc, char** argv)
{
    uid_t uid; //Declare it right here?
    if (argc < 2)
    {
        showUsage(argv[0]);
        return 0;
    }
    //Or should I declare uid_t variable here
    uid = getuid();
    if (uid > 0)
    {
        printf("\nroot privileges required!\n");
        return 0;
    }
  return 0;
}

I declare a uid_t variable above the first IF statement where I check if there're arguments to use. Does it make a difference when I declare the uid_t variable beneath the first IF statement? So, would it be 'more efficient' if I declare variables at that place when I'm sure that they are going to be used or does it make no difference?

Antrops
  • 31
  • 1

2 Answers2

3

There is no performance difference. The compiler will allocate variables in the most efficient way. Usually, this is done at the beginning of the function in one stack allocation step. However, you should always declare variables as late as possible and initialize them right away. This way, variables never have undefined values and can never accidentally be used prematurely.

Erlkoenig
  • 2,664
  • 1
  • 9
  • 18
2

Assuming a somewhat decent compiler, the resulting code will not differ at all, as in your case, both locations are the same scope.

So this is reduced to a simple stylistic question. I'd say the more widespread opinion nowadays is declare variables as close to their usage as possible, because this makes it easier to locally understand a piece of code.

If you follow this rule, you could also make sure that you declare a variable in the narrowest scope possible. As written above, it's no difference in your example, but it might very well be the case that you only need some variable in some nested block, then it shouldn't be visible outside this block.