does bool work in c(by this i mean a data type that can take only two states 0 or 1 in order to save memory)?
if yes then is it included in stdio or any other file is required to be included?
same doubt for c++
also mention the syntax for both!

Recommended Answers

All 4 Replies

If you're using C99 or later, then the underlying type is called _Bool, and you can include <stdbool.h> for macros that define the more convenient bool along with true and false. Prior to C99, there's technically no boolean type, though the integer types all work well as a facsimile.

In C++ bool, true, and false are all keywords.

In both languages the smallest storage for a boolean is one byte, despite the fact that they can only represent two values: true or false. This is because the smallest addressible unit in C and C++ is a byte, and boolean objects are addressible.

so when we use _bool 1 or 0 we dont need to include <stdbool.h>?
how to use _bool(can u plzz give a small program or prototype so i can clearly understand the syntax!)
how bool is used in c++..i mean syntax(is it like bool x;x=1;)

It's _Bool, not _bool. Case matters. ;) But yes, if you use _Bool, 0, and 1, then you don't need to include any headers.

can u plzz give a small program or prototype so i can clearly understand the syntax!

...

This is C (assuming C99 or newer):

#include <stdbool.h>
#include <stdio.h>

int main(void)
{
    _Bool x = 0;
    bool y = false;

    if (x) {
        puts("x is true");
    }
    else {
        puts("x is false");
    }

    if (y) {
        puts("y is true");
    }
    else {
        puts("y is false");
    }

    x = 1;
    y = true;

    if (x) {
        puts("x is true");
    }
    else {
        puts("x is false");
    }

    if (y) {
        puts("y is true");
    }
    else {
        puts("y is false");
    }

    return 0;
}

If <stdbool.h> is included, you can mix and match the defined keywords, such as bool x = 0, or _Bool x = false. The usage in C++ is the same, except _Bool is not an accepted keyword and you don't include any special headers.

thanxx it really helped :) !!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.