It seems there are many questions of the form "should I declare X?" but not this specific one. I hope it is ok to ask this.
The title says it all: why should I declare a pointer? Even better: there are risks if I do not declare the pointer? Consider the following examples:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <math.h>
#include <time.h>
#include <string.h>
void func(int *ptr);
int main (int argc, char **argv)
{
int a;
int *PTRa;
a = -1;
PTRa = &a;
func(PTRa);
printf("%d\n", a);
return 0;
}
void func(int *ptr)
{
*ptr = 1;
return;
}
I get a=1
. In this case I would say the pointer is declared (and assigned as well): I have the line int *PTRa;
(declaration) and the line PTRa = &a;
(assignment). The results is correct. I don't get any warning.
Imagine now to replace the main
with the following:
int main (int argc, char **argv)
{
int a;
a = -1;
func(&a);
printf("%d\n", a);
return 0;
}
Here I do not declare the pointer but just give the address of a
to func
. The result is correct and I don't get warnings.
My understanding is that the two approaches are identical: func
always gets the same input, the address of a
. I would even dare to say that I feel the second approach to be better, as I feel it to be clearer and I feel the variable PTRa
to be useless and somewhat redundant. However, I always see codes where the first approach is used and I have the feeling I will be told to do so. Why?