Home > Back-end >  Understanding function pointers in a simple calculator
Understanding function pointers in a simple calculator

Time:04-18

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
int add(int *a, int *b)
{
    return *a   *b;
}
int sub(int *a, int *b)
{
    return *a - *b;
} 
int mul(int *a, int *b)
{
    return *a * *b;
} 
int div(int *a, int *b)
{
    return *a / *b;
}
int main()
{
    char funcName[10];
    int num1, num2;

    scanf("%s %d %d", funcName, &num1, &num2);
    int (*fp)(int *,int*);
    if(strcmp(funcName,"add")==0)
        fp=add;
    if(strcmp(funcName,"sub")==0)
        fp=sub;
    if(strcmp(funcName,"mul")==0)
        fp=mul;
    if(strcmp(funcName,"div")==0)
        fp=div;
    else
        printf("Can't do that!");
    printf("%d\n", fp(&num1, &num2));
    return 0;
}

It's a simple code of pointer functions,but idk why this occurs.

when funcName=add,sub,mul(I'll take an example of sub),num1=5,num2=3

Can't do that!2

when funName=div,num1=5,num2=3

1

The answer is derived well whether or not I delete the "else" part, but I thought pointer fp is converted well to functions.. so the answer is derived...? However, why does "else" affects&why div isn't affected by "else"?

CodePudding user response:

if (a) {
  // sth0
}
if (b) {
  // sth1
}
else {
  // sth2
}

The else statement does not have anything to do with the first if statement.
If b is convertible to false, else is executed whether or not if (a) is.

What you want here is else if instead of ifs.

CodePudding user response:

This if-else statement

if(strcmp(funcName,"div")==0)
    fp=div;
else
    printf("Can't do that!");

always get the control

So if the function name was "sub" then the sub-statement of this if statement

if(strcmp(funcName,"sub")==0)
    fp=sub;

and the else part of this if statement

if(strcmp(funcName,"div")==0)
    fp=div;
else
    printf("Can't do that!");

will be executed.

If the function name is "div" then only the sub-statement

    fp=div;

of this if statement

if(strcmp(funcName,"div")==0)
    fp=div;
else
    printf("Can't do that!");

will be executed

You need to use if-else statements like

if(strcmp(funcName,"add")==0)
    fp=add;
else if(strcmp(funcName,"sub")==0)
    fp=sub;
else if(strcmp(funcName,"mul")==0)
    fp=mul;
else if(strcmp(funcName,"div")==0)
    fp=div;
else
    printf("Can't do that!");
  • Related