C enum declaration confusion | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

C enum declaration confusion

Consider this code: #include <stdio.h> int main() { enum Fruit {Apple, Orange}; enum Fruit p = Orange; int k = Orange; printf("%d\n%d", p, k); } All the tutorials in Google insist to use the first declaration (i.e. enum Fruit p). What is the problem with the second declaration using int? I don't see any point in typing out unnecessary keywords for no reason.

14th May 2021, 7:46 AM
Calvin Thomas
Calvin Thomas - avatar
2 Answers
+ 2
Consider a case where ORANGE have a value which is beyond the range of "int", in such case there would be no change in first declaration but the second line will have to undergo implicit conversion to the underlying type ( "int" in this case ) See this for example 👇 https://code.sololearn.com/cR9monr26FrG/?ref=app So using the first method of decleration not only make your code more human readable but also saves you from accidental type conversions.
14th May 2021, 8:32 AM
Arsenic
Arsenic - avatar
+ 1
Arsenic Thanks for the answer. That really helps.
14th May 2021, 9:18 AM
Calvin Thomas
Calvin Thomas - avatar