0

I CAN'T UNDERSTAND ENUM IN C++.

I am learning c++. now I am on enum. I can't understand for what does enum is used for in c++

27th Jul 2021, 7:30 AM
Pv slayer
Pv slayer - avatar
1 ответ
+ 9
Are you asking about how to use enums, or why we should use enums? My understanding is that you know how but you're not sure when to use them. Let's say you are building a function to accept only 3 colours: red, blue and green. You can represent them in your code as strings, or integers, e.g. processColor("red"); processColor(1); // where 1 is red, 2 is blue, etc The problem you face now is whoever uses your function is allowed to feed it whatever they want: processColor("myColor"); processColor(-39); You can do a check to accept only valid values, e.g. (color == "red") && (color == ... so on, by why don't you let the compiler check it for you? enum Color { red, blue, green }; If your function accept only the Color enum, not only does it make your code much more readable, whoever calls the function will need to use a value which exists only within Color. processColor(Color.red); With enums, compile time checking will limit the amount of mistakes one can make, and hence less code to check for errors
27th Jul 2021, 7:59 AM
Hatsy Rei
Hatsy Rei - avatar