Easy Tutorial
❮ Verilog2 Fifo Https Ssl Intro ❯

English: ## C Language Boolean Type (true and false)

Category Programming Techniques

The C language standard (C89) does not define a Boolean type. If you use true and false, the following error will occur:

infinite.c:5:12: error: use of undeclared identifier 'true'
    while (true) {

1 error generated.
make: *** [infinite] Error 1

We can use C language macro definitions to set up:

//Macro definition for Boolean type
#define BOOL int
#define TRUE 1
#define FALSE 0

//Define a Boolean variable
BOOL flag = FALSE;

You can also define it through an enumeration type:

typedef enum
{
    true=1, false=0
}bool;

Example

#include <stdio.h>

//Calculate the factorial of n, the value of n is defined in main
int main(void)
{
    int n = 10;    //Factorial calculation number
    int sum = 1; //Used to store the result of the factorial
    typedef enum
    {
        true=1, false=0
    }bool;
    bool flag = false;    //Factorial flag

    int num = n;    //Loop count
    while( !flag )
    {
        sum = sum * (num--);
        //End the loop when num=1
        if( num == 1)
        {
            flag = true;
        }
    }
    printf ("The factorial of %d is %d \n", n, sum);
    return 0;
}

The output result is:

The factorial of 10 is 3628800

C99 also provides a header file <stdbool.h> which defines bool as _Bool, true as 1, and false as 0. As long as you import stdbool.h, you can operate the Boolean type very conveniently.

Example

//Import stdbool.h to use the Boolean type
#include <stdbool.h>
#include <stdio.h>

//Calculate the factorial of n, the value of n is defined in main
int main(void)
{
    int n = 10;    //Factorial calculation number
    int sum = 1; //Used to store the result of the factorial
    bool flag = false;    //Factorial flag

    int num = n;    //Loop count
    while( !flag )
    {
        sum = sum * (num--);
        //End the loop when num=1
        if( num == 1)
        {
            flag = true;
        }
    }
    printf ("The factorial of %d is %d \n", n, sum);
    return 0;
}

The output result is:

The factorial of 10 is 3628800

** Click to Share Notes

Cancel

-

-

-

❮ Verilog2 Fifo Https Ssl Intro ❯