Boolean Type of C Language

Source: Internet
Author: User

No boolean type is defined in the C language standard (c89). Therefore, when the C language determines whether the true or false is true, 0 is false, and non-0 is true. Therefore, we usually use logical variables:

// Defines an int type variable. If the variable value is 0, it indicates false, and if the value is 1, it indicates true.
Int flag;
Flag = 0;
//......
Flag = 1;

If (FLAG)
{
//......
}

  

However, this method is not intuitive, and it is not clear that the flag must be a Boolean value. Therefore, we use the macro definition in C language:

// Macro defines the Boolean Type
# Define bool int
# Define true 1
# Define false 0

// Define a Boolean variable
Bool flag = false;

 

Although this method is intuitive, it is still a form of change. The variable flag is still of the int type in the compiler.

The new version will always improve some disadvantages, so the latest C language standard (c99) solves the Boolean Type problem. C99 provides the _ bool type, so the boolean type can be declared as _ bool flag.

_ Bool is still an integer type, but unlike general integer types, _ bool variables can only be assigned 0 or 1 values, and non-0 values are stored as 1.

C99 also provides a header file <stdbool. h> that defines bool AS _ bool, true as 1, and false as 0. You only need to import stdbool. h to operate the Boolean Type conveniently.

// Import stdbool. h to use the Boolean Type
# Include <stdbool. h>
# Include <stdio. h>

// Calculate n !, The value of N is defined in main.
Int main (void)
{
Int n = 10; // calculate the stacked Multiplier
Int sum = 1; // It is used to store the result of the stacked multiplication.
Bool flag = false; // stacked multiplication mark

Int num = N; // number of cycles
While (! Flag)
{
Sum = sum * (Num --);
// End the loop when num = 1
If (num = 1)
{
Flag = true;
}
}
Printf ("% d's stacked multiplication value is % d \ n", N, sum );
Return 0;
}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.