#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!!

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.

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!

>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); // [B]undefined[/B]: 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.

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.

Yes, I meant that very topic from the book. Thanks for the replies!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.