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?
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;
}
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?
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);
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");
}
}
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;
}
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.