'Called function work at printf but not at arithmetic statement
I made a struct Triangle and I made a function to calculate p(perimeter/2).
When I call the function inside printf it works.
But when I call the same function as a simple arithmetic statement it doesn't work and gives me following error
called object 'p' is not a function or function pointer
Source code:
#include <stdlib.h>
typedef struct{
int a, b, c;
} Triangle;
int perimeter (Triangle t){
return t.a + t.b + t.c;
}
float p (Triangle t){
return perimeter(t) / 2.0;
}
int main() {
Triangle t = {3, 4, 5};
//float p = p(t);
printf("p = %.2f\n",p(t));
return 0;
}
Solution 1:[1]
The line
float p = p(t);
defines a local variable p which shadows the global function p. This variable is of type float, so it is not a function or pointer.
Rename the variable to fix this.
Solution 2:[2]
//float p = p(t);
You cannot use the same name for a function and a variable. Change your float p to float a and it should work. Or rename your function to, say perimeter instead of just p.
Also in general, it is better to use slightly longer, clear and descriptive names for functions.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Bodo |
| Solution 2 | th33lf |
