pointers - C - Calculator with parameters -


i try create simple calculator c. numbers , operators should parameters. have main function , calculate function:

main:

int main(int argc, char *argv[]){     long result;     long number1 = strtol(argv[1], null, 10);     long number2 = strtol(argv[3], null, 10);      result = calculate(number1, number2, argv[2]);     printf("result: %li", result);      return 0; } 

calculate:

long calculate(long number1, long number2, char operator){     long result;      switch(operator){         case '+': result = number1 + number2; break;         case '-': result = number1 - number2; break;     }     return result; } 

when start program this:

./calc 1 + 2

the result 0. think there problem operator parameter, because when write '+' instead of argv[2] works. dont know how fix it, works parameter, too.

one problem calculate function expects char, main passes c string. problem when unexpected parameter passed, switch fails set result, leading undefined behavior.

one way compiler's in detecting issues provide prototypes functions ahead of point function gets called:

// put prototype first long calculate(long number1, long number2, char operator);  int main(int argc, char *argv[]){     // main's code call of calculate }  long calculate(long number1, long number2, char operator) {     // implementation } 

with prototype in place, compiler stops build error, because argv[2] not match expected type of char. problem becomes obvious you, insert missing asterisk, , program starts working expected.

you seeing warning second issue (not setting result in code paths); shouldn't ignore it, , add default clause produces output tells users went wrong.


Comments

Popular posts from this blog

javascript - Laravel datatable invalid JSON response -

java - Exception in thread "main" org.springframework.context.ApplicationContextException: Unable to start embedded container; -

sql server 2008 - My Sql Code Get An Error Of Msg 245, Level 16, State 1, Line 1 Conversion failed when converting the varchar value '8:45 AM' to data type int -