invalid operands to binary expression ('char ()' and 'int')

136 views Asked by At

`I've been trying this code to show if a number that I type is even or odd, but it gets an error when I run it:

ERROR:`

 make -s
./main.c:8:13: error: invalid operands to binary expression ('char ()' and 'int')
  if(numero % 2 == 0){
     ~~~~~~ ^ ~
1 error generated.
make: *** [Makefile:10: main] Error 1
exit status 2

CODE:

#include <stdio.h>

int main(void) {
   char number();
   printf("Enter a number: ");
   scanf("%d", &number);

   if (number % 2 == 0) {
     printf("%d is even", number);
   } else {
     printf("%d is odd", number);
   }

   return 0;
}

I tried searching the same error here, but it doesn't fix my error

3

There are 3 answers

0
JeremyP On

char number(); declares a function prototype because of the round brackets at the end. The compiler thinks number is a function returning a char. Therefore in

if (number % 2 == 0)

number is a function pointer and it makes no sense to divide it by 2.

number should be declared as an int if you are using %d i.e.

int number;
2
cartop On

the variable you use is of type char, in your case you need an integer

   #include <stdio.h>
`  int main(void) {
   int number;
   printf("Enter a number: ");
   scanf("%d", &number);

   if ( number % 2 == 0) {
     printf("%d is even", number);
   } else {
     printf("%d is odd", number);
   }

   return 0;
}
0
Vlad from Moscow On

In C initializers are supplied after the sign = in declarations

declarator = initializer

and (the C Standard, 6.7.9 Initialization)

11 The initializer for a scalar shall be a single expression, optionally enclosed in braces. The initial value of the object is that of the expression (after conversion); the same type constraints and conversions as for simple assignment apply, taking the type of the scalar to be the unqualified version of its declared type.

In this declaration in your program

char number();

there is absent the sign =. This line declares a function that has the return type char and unknown number and types of parameters.

If you want to declare an object of the type int according to these statements

printf("Enter a number: ");
scanf("%d", &number);

then declare it like

int number;

or you could initialize it with zero like

int number = 0;

or

int number = { 0 };

If your compiler supports C23 Standard then you can also write

int number = {};

It is desirable to check whether the input was successful. So you can write for example

if ( scanf("%d", &number) == 1 )
{
    if (number % 2 == 0) {
        printf("%d is even\n", number);
    } else {
        printf("%d is odd\n", number);
    }
}