What does the <stdbool.h> do when using it in a C code?
I searched for it on the Wikipedia and didn't get answers in my language, i would love that someone will explain to me what it means.
When the C Standard Committee finally added support for a boolean type in the C language in 1999 (C99), they did not want to create incompatible changes in the language semantics, thus they did not make bool, true and false new keywords that would have caused errors in programs already using these identifiers for types or variables, they only added the _Bool keyword for the boolean type, which was already a reserved identifier.
Yet to make these words available for new programs with standard semantics, they also added a new standard header file <stdbool.h> with this specification:
7.18 Boolean type and values <stdbool.h>
1 The header <stdbool.h> defines four macros.
2 The macro
bool
expands to _Bool.
3 The remaining three macros are suitable for use in #if preprocessing directives. They are
true
which expands to the integer constant ((_Bool)+1u),
false
which expands to the integer constant ((_Bool)+0u), and
__bool_true_false_are_defined
which expands to the integer constant 1.
4 Notwithstanding the provisions of 7.1.3, a program may undefine and perhaps then redefine the macros bool, true, and false.
I you want to use boolean variables in your program, include the <stdbool.h> header file, declare them with the bool type and use true and false as constant values.
Note that the phrase macros are suitable for use in #if preprocessing directives is achieved using a trick: true is defined as ((_Bool)+1u), not ((_Bool)1u) so #if true expands to #if ((_Bool)+1u), which ultimately expands to #if ((0)+1u) hence defines a block of source code to be compiled, whereas #if ((0)1u) would have cause a preprocessor error.
I have gone through the Wikipedia page linked above and over there it says this header file was introduced to C in the year 1999.
What I think is may be at that time we could not use the bool or true or false keywords as we are able to use now.
May be to use them at that time we would have had to include that header file
Related
Why does C use the word _Bool to define boolean values? Whereas they use the word float for floats and not _Float?
Furthermore, why does bool have to be included, why isn't part of the basic functionality, like float?
_Bool was not originally in C, but was added in the 1999 C Standard. If it had been called bool then a large amount of existing code would break because many projects made their own type alias bool already.
The C89 standard set aside identifiers starting with _ followed by upper-case character as reserved for implementation use. This is why new features added to C always start with such names. _Complex, _Alignof and _Static_assert are other examples.
There is also a header <stdbool.h> which aliases bool to _Bool and defines true and false ; this header can be included by new projects or by projects that didn't already define bool.
C did not originally have a Boolean type, it was added in the 1999 version of the language (C99). At that point, C++ was already standardized (in 1998) to use the type bool, with keywords false and true. To keep the C Boolean type separate from the one in C++, as well as preventing the new name from breaking old C code, it was named _Bool.
The reason why it was named with an underscore followed by an upper-case letter, is because such an identifier was already guaranteed not to exist in compiler, library or user code, by 7.1.3:
All identifiers that begin with an underscore and either an uppercase letter or another underscore are always reserved for any use.
"Reserved for any use" meaning reserved for future versions of the C language.
Therefore, all new language keywords that have been added to the language since C99 are named with underscore followed by first letter upper-case. Other examples from C99 are the types _Complex and _Imaginary.
For the cases where code compatibility with C++ was desired, the header <stdbool.h> was created. It contains the macro bool, which expands to _Bool. And also the macros false and true that expand to 0 and 1.
Though note that booleans are not fully integrated in the C language, as they are in C++. In C++, an expression such as a == b gives a result of type bool, with the value true or false. In C it gives a result of type int, with the value 1 or 0. This is for backwards-compatibility reasons with old C code.
As for ...
Furthermore, why does bool have to be included, why isn't part of the
basic functionality, like float?
... I observe that although you need to include stdbool.h to get bool, that's a convenience and C++-compatibility feature, not an essential. bool is an alias for _Bool, and in C99 and later you have _Bool automatically, but even that is non-essential. In C, any integer or pointer value can be interpreted as a boolean, with 0 or NULL being interpreted as false and all other values being interpreted as true. This was how boolean values were handled in C from the beginning, and it still works in implementations conforming to the latest standard.
In fact, type _Bool itself is just a special case of this very behavior: it is an integer type whose minimal requirements are that it be able to represent the values 0 and 1. In boolean context, it works just the same as any other integer type.
Any time I had the need of a Boolean type I was told to either create one, or better yet, use stdbool.h.
Since stdbool.h uses typedef bool _Bool, is there a reason to use the header instead just using type _Bool? Is it just for the additional macros (/* #define true 1 #define false 0 */)?
The obvious type to add into the language was bool. But unfortunately, plenty of code was written that included bool in other shapes and forms. Recall that support for a boolean type was added only in C99.
So the C language committee had no choice but to pull out a reserved identifier for it (_Bool). But, since the obvious choice of type name is still the same, stdbool.h was added to allow users the obvious name. That way, if your code didn't have a home-brewed bool, you could use the built in one.
So do indeed use stdbool.h if you aren't bound to some existing home-brewed bool. It will be the standard type, with all the benefits that type brings in.
The common practice has always been to use bool but when the type was officially introduced into the standard in C99, they didn't want to break the "roll-your-own" implementations. So they made the type _Bool as kind of a hack around the unofficial bools. Now there's no type name collision. Anyway, point is, use bool unless a legacy codebase breaks.
They are same. bool is an alias for _Bool.
Before C99 we used we dont have this type. (Earlier the use was limited to an integer tyoe with 0 as false and 1 as true).
You may not use it. Even you can undef bool (but it is recommended not to do so). But including it (stdbool.h and bool alias of _Bool) is good because then if someday it becomes reserved your code complies to that.1
1. You can use bool other way but it is better not to. Because in general when this stdbool.h is introduced it bears the plan of gradually making it standard and then even more stricter rule applies where we can't use bool as something other and it will be reserved as keyword.
In many places I see the usage of undefine macro before defining the same macro. For example:
#undef FORMULA
#ifdef SOMETHING
#define FORMULA 1
#else
#define FORMULA 2
#endif
What for the #undefine FORMULA used?
I may guess that it deals with the case when the macro was already defined before. But isn't the new definition overrides the old one? Thanks!
A macro name currently defined cannot be redefined with a different definition (see below), so #undef allows that macro name to be redefined with a different definition.
Here's the relevant legalese:
Both C and C++ Standards (same wording):
A macro definition lasts (independent of block structure) until a corresponding #undef directive is encountered or (if none is encountered) until the end of the preprocessing translation unit.
Slight differences in wording, same meaning:
C Standard (N1256), §6.10.3/2:
An identifier currently defined as an object-like macro shall not be redefined by another #define preprocessing directive unless the second definition is an object-like macro definition and the two replacement lists are identical. Likewise, an identifier currently defined as a function-like macro shall not be redefined by another #define preprocessing directive unless the second definition is a function-like macro definition that has the same number and spelling of parameters, and the two replacement lists are identical.
C++ Standard (N3337) §16.3/2
An identifier currently defined as an object-like macro may be redefined by another #define preprocessing directive provided that the second definition is an object-like macro definition and the two replacement lists are identical, otherwise the program is ill-formed. Likewise, an identifier currently defined as a function-like macro may be redefined by another #define preprocessing directive provided that the second definition is a function-like macro definition that has the same number and spelling of parameters, and the two replacement lists are identical, otherwise the program is ill-formed.
Same wording in both Standards:
Two replacement lists are identical if and only if the preprocessing tokens in both have the same number, ordering, spelling, and white-space separation, where all white-space separations are considered identical.
So:
#define X(y) (y+1)
#define X(z) (z+1) // ill-formed, not identical
IMHO, using #undef is generally dangerous due to the scoping rules for preprocessor macros. I'd prefer to get a warning or error from the preprocessor and come up with a different preprocessor macro rather than have some translation unit silently accept a wrong macro definition that introduces a bug into the program. Consider:
// header1.h
#undef PORT_TO_WRITE_TO
#define PORT_TO_WRITE_TO 0x400
// header2.h
#undef PORT_TO_WRITE_TO
#define PORT_TO_WRITE_TO 0x410
and have a translation unit #include both headers. No warning, probably not the intended result.
Yes, the new definition overrides all previous. But there is corresponding warning message. With #undef you have no warnings.
But isn't the new definition overrides the old one?
Yes, it does (when your compiler allows it). However, redefining a macro results in a compiler warning, which using #undefine lets you avoid.
This may be important in programming shops with strict rules on compiler warnings - for example, by requiring all production code to be compiled with -Werror flag, which treats all warnings as errors.
#undef removes the macro, so the name is free to be defined again.
If the macro was never defined in the first place, #undef has no effect, so there's no downside. #undef … #define should be read as replacing any potential previous definition, but not to imply that it must already be defined.
Popular compilers do allow you to skip the #undef, but this is not allowed by the official standard ISO C and C++ language specifications. It is not portable to do so.
If a compiler has a certain type (ex. ptrdiff_t) as an embedded type, I don't want to typedef it again. I know that below code does not work properly that I expected.
#ifndef ptrdiff_t
typedef long int ptrdiff_t;
#endif
How can I check a certain type is already defined in the C compiler?
As others have said, there is no good general solution to this. Type names are not visible to the preprocessor, so you can't use #ifdef to test for their existence.
There are a number of partial solutions, though, and they vary depending on where the requirements for a given type came from.
There are several versions of the ISO C standard, issued in 1990, 1999, and 2011. Each new standard (in theory) supersedes and replaces the previous one, and each one defines some new types. For example the 1999 C standard added headers <stdbool.h> and <stdint.h>, and types bool, int32_t, etc. If you want to use the bool type, but still want your code to be portable to implementations that don't support C99, you can do something like:
#if defined(__STDC__) && __STDC_VERSION__ >= 199901L
#include <stdbool.h>
#else
typedef enum { false, true } bool;
#endif
The enum type doesn't behave exactly like C99's built-in bool type, so you need to be a little careful in how you use it.
The type uintptr_t, defined in <stdint.h> is optional. It's an unsigned type that can hold a converted void* pointer value without loss of information; an implementation that has no such unsigned type (say, because pointers are bigger than any integer type) won't provide it. You can't directly test for the type itself, but you can test for the macros that give its bounds:
#include <stdint.h>
#ifdef UINTMAX_MAX
/* uintmax_t exists */
#else
/* uintmax_t doesn't exist */
#endif
You may need to wrap this in a test for __STDC__ and __STDC_VERSION__ if you can't assume C99 or better.
The type long long is a predefined type (not part of the library), added in C99. Again, you can't test for it directly, but you can test for the macros that define its bounds:
#include <limits.h>
#ifdef LLONG_MAX
/* long long exists */
#else
/* long long *probably* doesn't exist */
#endif
Finally, there are things you can't do directly in C, but that you can do as part of your program's build process. For example, POSIX defines a type pid_t in the POSIX-specific header <unistd.h> (it's the type of a process identifier, returned by the getpid() function). You can't conditionally include a header -- but you can write a small program that will fail to compile if the header doesn't exist:
#include <unistd.h>
pid_t dummy;
As part of your build process, try to compile this file. If it succeeds, append a line like
#define HAVE_PID_T
to a configuration header; if it fails, append a line like
#undef HAVE_PID_T
In your source code, you can then write something like:
#include "config.h"
#ifdef HAVE_PID_T
#include <unistd.h>
/* pid_t exists */
#else
/* pid_t doesn't exist */
#endif
GNU Autoconf provides a way to automate this kind of test, but it's been criticized for being overly complex and unwieldy.
All of this assumes that, once you've determined whether a type exists, you can do something useful with that information. For some types, like bool, you can implement a nearly equivalent alternative. For pid_t, on the other hand, there likely isn't a good fallback, unless you simply #ifdef out all the code that deals with processes. If your program just isn't going to work on a system that doesn't have pid_t and getpid(), it might be best to just write code that assumes they exist. If you try to compile your code on a system that doesn't provide them, it will immediately fail to compile, and that may be the best thing you can do.
There's no way to do that in general. In some cases there may be a macro that is defined at the same time as the type that you can use.
In your particular example, you can #include <stddef.h>, which should always define ptrdiff_t.
In your question you are a bit confusing 2 different things:
There are built in types, like int, float, etc. These are standard types and they are defined is all compilers. Types like __int64 were introduced and standardized later. This means that they are defined in all recent compilers but only in some of the older compilers. You do not need to do anything to use them. At the same time you cannot figure out in your code if they are defined or not. This can be figured out only from the docs on the compiler. You can write:
#ifdef MSVC
.... Microsoft specific code
#else
.... Code for other compiler.
#endif
This approach allows you to create sort of compiler independent environment.
Besides the built in types, there are types that come from the headers. Some headers have constructs like:
#ifndef ptrdiff_t_DEFINED
#define ptrdiff_t_DEFINED
typedef long int ptrdiff_t;
#endif
Note that the macro-processor definitions stay apart from the definition of the type. You cannot check if the type is defined or not, but you can easily check if a macro definition is defined.
What headers are included in your code you deside yourself. This means that these definitions are not in the compiler itself. They are in the set of definitions of the current translation unit. For compiler they have little difference from other type definitions that you write in your own code.
Some compiler or system headers for not have "guarding defns" like in the example above. In this case the only thing that you can do is to track from what headers thay are coming and include/not include these headers, maby using your own #ifdef guards around the #include statements.
Since redefining a C language reserved construct would generally lead to a compile time error, it is not possible to check it in general.
If you are interested(for academic/learning process), you can write a basic compiler pass to check for exceptions/errors on your C program to detect if a type is reserved or not.
I have a double type bool so have added to a header:
typedef double bool;
extern bool true;
extern bool false;
with:
bool true = 1.0;
bool false = 0.0;
in the corresponding C file.
However I now have the errors multiple definition of true, and the same for false, pointing to the first line of the first function in the C file. the error that says 'previous declaration was here' points to the same line... it doesnt make any difference which function is placed first in the file it always points to it.
My header files, though included via a common header file, do have include guards so I hopefully shouldn't have multiple declaration of true and false there.
I have changed the typedef to tBool with vars tTrue and tFalse, which solves the problem, but I don't get why it occurred in the first place? As there are still some bool types using true and false in the code it seems like the compiler may have a definition for true and false as ints already... though I didn't think C did this
Im using dev-c++ 4.9.9.2 IDE that uses mingw, though Im not sure which version mingw.
Anyone know why this happened?
It sounds to me like your parameter is not really a Boolean value at all. You have a floating point parameter with special cases for the discrete numbers 0.0 and 1.0. Create two double constants instead of a type.
C99 added definitions for the type _Bool, a macro bool, a macro true, and a macro false. Try inserting the following in your header:
#if __bool_true_false_are_defined
# error "stdbool.h has been included"
#endif
#ifdef bool
# error "bool is already DEFINED"
#endif
#ifdef true
# error "true is already DEFINED"
#endif
#ifdef false
# error "false is already DEFINED"
#endif
If any of these fire, then you are including stdbool.h somewhere. You should be able to #undef the three macros and then set up your types safely. Of course, this will probably break if someone else expects bool to be a small integer value and has more style problems that you can shake a stick at.
ISO/IEC 9899:1999 does make a concession to the fact that many groups have already defined their own Boolean types before it was added to the Standard. This is the rationale for defining bool, true, and false as macros instead of new keywords. However, the following warning is explicitly included:
7.26.7 Boolean types and values <stdbool.h>
The ability to undefine and then perhaps redefine the macros bool, true, and false is an obsolescent feature.