JonOsterman JonOsterman - 1 month ago 22
C Question

Return boolean with ternary operator

I made this code to know of my input is a multiple of two

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

bool main(int ac, char **av)
{
if (ac == 2)
{
int nb = atoi(av[1]);
(((nb / 2) * 2) != nb) ? false : true;
}
}


But gcc is returning me this :

test.c:5:1: error: unknown type name ‘bool’
bool main(int ac, char **av)
^
test.c: In function ‘main’:
test.c:10:32: error: ‘false’ undeclared (first use in this function)
(((nb / 2) * 2) != nb) ? false : true;
^
test.c:10:32: note: each undeclared identifier is reported only once for each function it appears in
test.c:10:40: error: ‘true’ undeclared (first use in this function)
(((nb / 2) * 2) != nb) ? false : true;


I precise I'm under Ubuntu bash for Windows (I haven't access to any Linux now)

I don't understand why I can't use bool type for my function, or why 'false' and 'true' aren't recognised

Answer Source

You have a number of issues in your code.

First of all you miss the return keyword here:

return (((nb / 2) * 2) != nb) ? false : true;
^^^^^^

Besides that you don't need a ternary operator as the first part is all ready a bool. So simply do:

return (((nb / 2) * 2) == nb);
^^^^^^                 ^^

Further you don't have a return statement in the code when ac isn't equal 2.

Also you should include stdbool.h to use bool.

Finally the main function must return an int - not a bool.

A rewrite of your code could be:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdbool.h>   // Include this to use bool

bool foo(int ac, char **av)
{
  if (ac == 2)
  {
      int nb = atoi(av[1]);
      return (((nb / 2) * 2) == nb); 
  }

  return false;
}

int main(int ac, char **av)
{
    if (foo(ac, av))
    {
        printf("foo returned true\n");
    }
    else
    {
        printf("foo returned false\n");
    }

    return 0;
}