C Interview Questions and Answers

 

What is the right type to use for Boolean values in C? Is there a standard type? Should I use #defines or enums for the true and false values?

Traditionally, C did not provide a standard Boolean type, partly and partly to allow
the programmer to make the appropriate space/time tradeoff. (Using an int may be
faster, while using char may save data space. Smaller types may make the generated
code bigger or slower, though, if they require lots of conversions to and from int.)



However, C99 does define a standard Boolean type, as long as you include <stdbool.h>.



If you decide to define them yourself, the choice between #defines and enumeration
constants for the true/false values is arbitrary and not terribly interestingUse
any of



#define TRUE 1 #define YES 1



#define FALSE 0 #define NO 0





enum bool {false, true}; enum bool {no, yes};



or use raw 1 and 0, as long as you are consistent within one program or project.
(An enumeration may be preferable if your debugger shows the names of enumeration
constants when examining variables.)



You may also want to use a typedef:



typedef int bool;



or



typedef char bool;



or



typedef enum {false, true} bool;





Some people prefer variants like



#define TRUE (1==1)



#define FALSE (!TRUE)



or define ``helper'' macros such as



#define Istrue(e) ((e) != 0)

Posted by:Richards