DaniWeb IT Discussion Community

DaniWeb IT Discussion Community (http://www.daniweb.com/forums/)
-   C++ (http://www.daniweb.com/forums/forum8.html)
-   -   enum range (http://www.daniweb.com/forums/thread32837.html)

aminura Sep 24th, 2005 4:36 am
enum range
 
#include<iostream.h>
int main()
{
        enum flag{ x=1,y=2,z=4,e=8};
        flag f2=flag(99); // out of range
        return 0;
}

In this code the range of flag is 0:15 but it still compiles when 99 is entered which is out of range!!

Narue Sep 24th, 2005 10:20 am
Re: enum range
 
So? C++ doesn't try to stop you from trying to do stupid things. How about instead of asking why you can do something blatantly wrong, DON'T DO IT TO BEGIN WITH.

aminura Sep 24th, 2005 11:16 am
Re: enum range
 
Well, I tried this because this was given as an example in Bjarne Stroustrup's book..but I couldn't get the result he specified!

Narue Sep 24th, 2005 3:49 pm
Re: enum range
 
>I tried this because this was given as an example in Bjarne Stroustrup's book
If you're citing a reference, give us sections and/or page numbers. Luckily, I both have that book and know what part of it you're talking about. It's page 77 in my most recent copy, section 4.8, Enumerations.

>but I couldn't get the result he specified!
You must have missed the comment:
flag f4 = flag(99); // undefined: 99 is not within the range of flag
Undefined means you can do it and the compiler probably won't even warn you, but it's not guaranteed to do anything expected, and there's nothing stopping undefined behavior from doing very real damage. I've heard stories of undefined behavior blowing out CRT monitors and wiping hard drives. Granted, that's an extreme, but the possibility should be more than enough to get you thinking.

Ancient Dragon Sep 24th, 2005 9:37 pm
Re: enum range
 
c and c++ compilers do not do range checking on enumerations or pointers. It lets you hang yourself with a very very long rope if you want to. Its up to the programmer to validate data ranges and buffer sizes before using or doing something with them. Those are two very good reasons for c++ programs to use the STL classes.

aminura Sep 25th, 2005 3:10 am
Re: enum range
 
Yes, I meant that very topic from the book. Thanks for the replies!


All times are GMT -4. The time now is 2:31 pm.

Forum system based on vBulletin Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
©2003 - 2008 DaniWeb® LLC