Home > Back-end >  Called function work at printf but not at arithmetic statement
Called function work at printf but not at arithmetic statement

Time:04-30

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;   
}

CodePudding user response:

//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.

CodePudding user response:

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.

  • Related