problem with enum

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

#include <iostream>
using namespace std;

enum WORKDAY  { SUN, MON, TUE, WED, THU, FRI, SAT};

void main(void)
{
	WORKDAY date;

	date = static_cast<WORKDAY>(date + 10);
	cout << date << endl;

	system("pause");
}


When I tried to complie this code,the compiler didn't report any syntax error. But the program crashed as soon as I ran it. So I guess the problem lies in line 8 where
date
goes out of range. The thing is, when I compiled this same piece of code using another compiler, nothing went wrong~! I got
17
as the output.

So the question is, is this kind of "problem" really compiler dependent?
I don`t quite understand what your objective is.
WORKDAY is the name of enum. and enum is an enumeration type. If you call WORKDAY SUN it will return 0.
In main() line 9 you seem to be declaring date as a WORKDAY type which it is not. Also I have no idea what line 11 is meant to do.
It crashes? Well, in terms of standard complaint C++ it certainly is allowed to crash, but I woul expect it just to print out rubbish.

Anyway, date is an enum and it is not initialized before you access it in line 11. (The "date + 10" is an access, which comes before the "date =", so you are accessing uninitialized memory). The standard says about this (analogously): "you'll die!". But in real compilers, it should just print out some rubbish number.

Still, what buffbill says is true: Is there any purpose other than "trying something strange-looking" with your code? :-D

Ciao, Imi.
Last edited on
The way enumeration works is a little bit different.

The enumerators (elements of enumeration - SUN, MON, ...) are just symbols you can use for your convenience instead of integers (however they are stored as integers internally).

So you can type date = MON; instead of date = 1; etc. No casting!

Naturally cout's output would be an integer value.
Topic archived. No new replies allowed.