MinhHoang
MinhHoang

Reputation: 711

What is best approach to define function which takes true or false as parameter in C

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?

Upvotes: 1

Views: 309

Answers (6)

user142162
user142162

Reputation:

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);

Upvotes: 0

ob_dev
ob_dev

Reputation: 2838

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?

Upvotes: 2

user418748
user418748

Reputation:

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

Upvotes: 0

EvilTeach
EvilTeach

Reputation: 28882

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;
}

Upvotes: 0

M S
M S

Reputation: 4093

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");
    }   
}

Upvotes: 0

Alok Save
Alok Save

Reputation: 206656

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;
}

Upvotes: 2

Related Questions