1

I got the below code example from my textbook, and it's still not compiling.

I get an error on the printf line that says Unary '++': 'months; does not define this operator or a conversion to a type acceptable to the predefined operator.

I don't know what to do because this is the first time I've ever attempted enumeration, and this is literally the example code from the book. What's wrong with it?

// Fig. 10.18: fig10_18.c
// Using an enumeration

#include <stdio.h>

// enumeration constants represent months of the year            
enum months {                                                    
    JAN = 1, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC
}; 

int main(void) { 
    // initialize array of pointers
    const char *monthName[] = { "", "January", "February", "March", 
      "April", "May", "June", "July", "August", "September", "October",
      "November", "December" 
    };

    // loop through months
    for (enum months month = JAN; month <= DEC; ++month) {
        printf("%2d%11s\n", month, monthName[month]);
    } 
}
chqrlie
  • 131,814
  • 10
  • 121
  • 189
JQD
  • 73
  • 7
  • 3
    Sounds like you are using a C++ compiler? – Eugene Sh. Apr 05 '19 at 17:11
  • Possible duplicate of [looping through enum values](https://stackoverflow.com/questions/1662719/looping-through-enum-values) – Random Davis Apr 05 '19 at 17:12
  • Yes! I just changed my file extension from .cpp to .c, and it worked. Thanks so much! – JQD Apr 05 '19 at 17:16
  • In C++ an enum is a distinct type which does not support setting back to the enum or increment/decrement operations. In C the enum is really just an integer. Find out how to tell your compiler to build C code, as this will allow other example code to work as-is. To fix this particular case you could change `enum months month` to `int month` – Gem Taylor Apr 05 '19 at 17:16
  • @Emily: you can accept one of the answers by clicking on the grey checkmark below its score. – chqrlie Apr 13 '19 at 11:44

1 Answers1

0

What you do is correct in C but incorrect in C++.

You must use a C compiler instead of a C++ compiler.

You could try and use the -x c command line option to tell the C++ compiler to compile the source file as C code.

chqrlie
  • 131,814
  • 10
  • 121
  • 189