This is my code:
#include <stdlib.h>
#include <stdio.h>
int sum(int,int);
int sum(int x, int size) {
int sum = 0;
printf("%p\n", &x);
printf("%p\n", &size);
printf("%p\n", &sum);
sum(x,size);
return 0;
}
int main() {
sum(2,4);
return 0;
}
And the error I am getting is:
hello.c:11:5: error: called object type 'int' is not a function or function pointer
sum(x,size);
~~~^
If you define two separate identifiers of same name for different entities in the same name space, they might overlap.
C11
standard, chapter §6.2.1 states,Refer Footnote: Why in this scenario, both
sum
s are in same name spaceSo, once you re-define the identifier with some other type,
That means, essentially, in your case, inside function
sum()
, when you're definingint sum
, basically you're shadowing the functionsum
. After the re-definition,sum
is an identifier of typeint
, in that function scope. Thus, inside the functionsum()
, you cannot make a call tosum()
as that is anint
type now.However, FWIW, the call to
sum()
inmain()
(or, rather, outsidesum()
itself) should be valid, as at that point,int sum
will be out of scope.Solution: Change the
int sum
variable name to something else.Thanks to @pmg for the correction
EDIT:
As mentioned in the other answer by @juanchopanza, after changing the shadowing variable name, your program will compile and once you run it, you'll face infinite recursion due to the unconditional call to
sum()
insidesum()
itself. You need to add some break condition to end (return
from) the recursion.FootNote:
Referring to
C11
, chapter §6.2.3, name spaces, we can say, there are separate name spaces for various categories of identifiers, e.g. 1) label names 2) the tags of structures, unions, and enumerations, 3) the members of structures or unions and 4) all other identifiers.So, in this particular case, the function
sum()
and theint sum
definition will reside in the same name space, for thesum()
function scope