Search code examples
cpointerspass-by-reference

Declaring all variables as pointers vs. using address operators in C


The following two blocks of code do the same thing:

void foo(int *num) {...}

int main(void)
{
    int num = 5;
    foo(&num);

    ...
}
void foo(int *num) {...}

int main(void)
{
    int *num;
    *num = 5;
    foo(num);

    ...
}

In both cases foo expects a pointer-to-int argument. In the first I declare an int and use the address operator (&) to pass it into foo. In the second I declare a pointer variable and directly pass it into foo.

Is there a reason to use either one, other than a stylistic preference? I prefer to declare all of my variables as pointers, as in the second, but I see the first a lot more frequently.


Solution

  • While the first code snippet gets the address of a variable and passes that to foo, the second dereferences an uninitialized pointer. What you instead could have done was:

    int *num = malloc(sizeof(int));
    *num = 5;
    
    foo(num);
    
    free(num);
    

    Or:

    int num = 5;
    int *p = #
    foo(p);
    

    The main thing to take away from this is that the first form is the simplest. A valid pointer variable must be pointing to memory within your program's control, and that requires more work than just int *num; *num = 5;