3

I am making a basic calculator to get familiar with passing arguments. The function I coded is:

int op(char* sig, int num1, int num2)
{
    char sign=*sig;
    if(sign == '+') return num1+num2;
    if(sign == '/') return num1/num2;
    if(sign == '-') return num1-num2;
    if(sign == '*') return num1*num2;
    return 0;
}

My main function grabs the numbers and the sign and calls the "op" function.

int main(int argc, char *argv[])
{
    int num1=atoi(argv[1]);
    int num2=atoi(argv[3]);
    char* sig=argv[2];
    int res=op(sig,num1,num2);
    printf("%d\n",res);
}

The problem is when I call the program through the terminal using the "./" command it doesn't take the * sign as a char. Instead when I use * in the arguments, that argument becomes pipewriter.c which is the name of the file where I coded this. For example, ./pw.exe 3 + 4 prints 7 while ./pw.exe 3 * 4 just prints 0.

How can I use the * sign as just a '*' character?

Chris
  • 26,361
  • 5
  • 21
  • 42
Johan
  • 41
  • 1
  • 4

1 Answers1

9

* is a special character to the shell (used for filename globbing), so if you want to pass one literally to your program as an argument you need to quote or escape it:

  • '*'
  • "*"
  • \*

The difference between these three (and why you might want to use one over another) is in how they interact with variable expansions. For your purposes (with no shell variables involved), any of them will do.

Chris Dodd
  • 119,907
  • 13
  • 134
  • 226