1

I am a bit confused by what for and where enum is good? What are the benefits of using enum against defining global variables (constants) or macros? For instance in this code:

#include<stdio.h> enum bool {false, true}; int main() { enum bool b = 100; printf("%d", b); return 0; } 

I can assign even any integer value to b and every thing works fine, so why not doing

int false = 0, true = 1; 

or

#define false 0 #define true 1 

in the global scope? Can some one explain where and why are enums useful and should be preferred to use?

8
  • If you use the enum type, the compiler understands all possible values for the value. Commented Aug 2, 2021 at 21:32
  • You can use the enum type when declaring variables and functions. Commented Aug 2, 2021 at 21:33
  • 5
    It makes the intent self-documenting. If you just declare the variable to be int, there's no way to tell that it should only contain ` true/false` value. Commented Aug 2, 2021 at 21:34
  • 1
    Enumerations are good for representing small sets of values that aren't normally ordered, or where arithmetic operations aren't meaningful (an example I gave in another answer was enum cartype { sedan, suv, hatchback, coupe };). One advantage of using enumeration constants over preprocessor macros is that the constant name is preserved in debuggers, where the macro is not (e.g., if you have an object enum cartype car = sedan; and you examine the value in the debugger, the debugger will show sedan instead of 0). Commented Aug 2, 2021 at 22:21
  • 2
    Side-note: you should use C's stdbool instead of defining your own true/false values. Commented Aug 2, 2021 at 22:23

1 Answer 1

3

There are many advantages to using enum over #define macros:

Advantage and disadvantages of #define vs. constants?

The use of an enumeration constant (enum) has many advantages over using the traditional symbolic constant style of #define. These advantages include a lower maintenance requirement, improved program readability, and better debugging capability.

I would also encourage you to use bool (and <stdbool.h>) instead of an enum for true/false.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the links, however I am more interested in enums rather than booleans here!
Please read the links I cited (you can easily find many others!) on "enum". To explicitly answer your question "Q: when should I use them?" A: Just about whenever possible :) One big exception: generally, you should NOT use enums in preference to "bool" for true/false values (as in your example). Nor should you use "int true=1" or equivalent. I hope that helps :)