1

As title stated, I'm writing function taking 2 boolean as parameters but don't know what is the best way to do! What are your suggestions?

MinhHoang
  • 681
  • 3
  • 9
  • 22

6 Answers6

2

c99 already provides the bool data type if you are using that, you can use it directly.

Else another ways are:

Simple way: Use integers and treat 0 as false and 1 as true.

Verbose way: Create enum with true and false names and use that.

Code Sample:

typedef enum 
{
    FALSE = 0,
    TRUE = 1
}Boolean;

int doSomething(Boolean var1, Boolean var2)
{
   if(var1 == TRUE)
    return 1;
    else
    return 0;
}

int main()
{
    Boolean var1 = FALSE;
    Boolean var2 = TRUE;

    int ret = doSomething(var1,var2);

    return 0;
}
Alok Save
  • 202,538
  • 53
  • 430
  • 533
2

You can use the C99 bool type

#include <stdbool.h> //don't forget to include this library

void func(bool a, bool b)
{


}

int main(void)
{
     bool a = true, b = false;
     func(a, b);
     return 0;
}

take a look at : C99 boolean data type?

Community
  • 1
  • 1
ob_dev
  • 2,808
  • 1
  • 20
  • 26
0

Using two int values should work fine:

void func(int x, int y)
{
   if(x) // x is non-zero
   {
      // do something
   }
   if(y) // z is non-zero
   {
      // do something
   }
}
func(0, 1); // x is false, y is true

You could #define true and false to be something like 1 and 0:

#define FALSE 0
#define TRUE 1
func(FALSE, TRUE);
0
typedef enum boolean_t{
    FALSE = 0,
    TRUE
}boolean;

int main(){
    fun1(TRUE);
}

int fun1(boolean val)
{
    if (val == TRUE){
        printf("True\n");
    }else{
        printf("False\n");
    }   
}
M S
  • 3,995
  • 3
  • 25
  • 36
0

Try something like this. An int can act like a bool. Zero is false. Everything else is true.

#include <stdio.h>

void function (int boolValue)
{
    if (boolValue)
    {
        printf("true");
    }
    else
    {
        printf("false");
    }
} 

int main(void)
{
    function(1 == 2);
    function(1 > 2);

    return 0;
}
EvilTeach
  • 28,120
  • 21
  • 85
  • 141
0

If size matters to you, you could as well try (assuming you only have a C89 Compiler)

#define false 0
#define true  1
typedef char Boolean;

//...
Boolean test = true;
if( test )
    puts("Heya!");
else
    puts("Not Heya!");
//...

and your Boolean is guaranteed to have sizeof() == 1