I'm just trying to learn c and I'm stuck. I'm trying to create a program that can take an input of two numbers, together with an operator and print out the answer.
The notation is reversed polish notation. That is to say, the input 2 1 + should give the output 3, the input 2 1 * should give the output 2.
Later, I will expand it so that you can enter longer expressions in rpn with some stack based stuff but lets focus on the case with just two operands for now.
This is what I have done:
#include <stdio.h>
main()
{
int number1;
int number2;
char operator;
scanf("%d %d %c", &number1, &number2, &operator);
printf("%d", calculate(number1, number2));
}
int calculate(int number1, int number2)
{
return number1+number2;
}
This works at suspected and it writes out the sum of number1 and number2. However, when I try passing a character as an argument to the function calculate, like this
#include <stdio.h>
main()
{
int number1;
int number2;
char operator;
scanf("%d %d %c", &number1, &number2, &operator);
printf("%d", calculate(number1, number2, operator));
}
int calculate(int number1, int number2, char operator)
{
return number1+number2;
}
I get a compile error
rpn.c:12:5: error: conflicting types for ‘calculate’
rpn.c:13:1: note: an argument type that has a default promotion can’t match an empty parameter name list declaration
rpn.c:9:15: note: previous implicit declaration of ‘calculate’ was here
Is it not possible to pass a char as an argument in c? I don't understand why this isn't working when it works with int. I have googled on this a lot, but the questions usually only covers passing an array of chars as an argument, not a char.
Or am I doing this all wrong?
Put the calculate()
function above the main()
function. The compiler needs to know about the function before it can call it.
Alternatively you can forward-declare it above main
by including this line before main()
:
int calculate(int number1, int number2, char operator);
It will also help to turn on warnings in your compiler. With GCC you can use -Wall
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With