-
March 26th, 2012, 11:04 PM
#1
Problem with enum
I am trying to run an example from a book I read.
"
#include <stdio.h>
enum months { Jan,Feb,Mar,Apr,Jun,Jul,Aug,Sep,Oct,Nov,Dec};
int main()
{
enum months month;
const char* monthName[]= { "","January","February","March","April","May","June","July","August","September","October","November","December"};
for (month=Jan;month<=Dec;month++)
printf("%2d%11s\n",month,monthName[month]);
return 0;
}
"
This code gives these errors:
main.cpp:35: error: no 'operator++(int)' declared for postfix '++', trying prefix operator instead
main.cpp:35: error: no match for 'operator++' in '++month'
Like you see "month++" in for loop's beginning gives the error but in the book it is written as that...
Last edited by AwArEnEsS; March 26th, 2012 at 11:15 PM.
-
March 27th, 2012, 01:23 AM
#2
Re: Problem with enum
It isn't giving any error for me.
Code:
$ gcc -g 1.c
$ ./a.out
0
1 January
2 February
3 March
4 April
5 May
6 June
7 July
8 August
9 September
10 October
Although the o/p might not be the same that you want.
For the correct o/p, your code would be
Code:
#include <stdio.h>
enum months { Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec};
int main()
{
enum months month;
const char* monthName[]= { "January","February","March","April","May","June","July","August","September","October","November","December"};
for (month=Jan;month<=Dec;month++)
printf("%2d%11s\n",month+1,monthName[month]);
return 0;
}
-
March 27th, 2012, 03:03 AM
#3
Re: Problem with enum
Originally Posted by AwArEnEsS
This code gives these errors:
Please use code tags when posting code.
Originally Posted by AwArEnEsS
main.cpp:35: error: no 'operator++(int)' declared for postfix '++', trying prefix operator instead
main.cpp:35: error: no match for 'operator++' in '++month'
Like you see "month++" in for loop's beginning gives the error but in the book it is written as that...
You cannot increment an enum. Make your loop counter an integer and it will compile.
Code:
#include <stdio.h>
enum months { Jan, Feb, Mar, Apr, Jun, Jul, Aug, Sep, Oct, Nov, Dec };
int main()
{
const char* monthName[]= { "", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" };
for (int month = Jan; month <= Dec; month++)
printf("%2d%11s\n", month, monthName[month]);
return 0;
}
Also, note how much easier this code is to read when you use the space bar once in a while.
Cheers, D Drmmr
Please put [code][/code] tags around your code to preserve indentation and make it more readable.
As long as man ascribes to himself what is merely a posibility, he will not work for the attainment of it. - P. D. Ouspensky
-
March 28th, 2012, 12:12 AM
#4
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|