Friday, August 8, 2008

Am I finally surpised or just about to pass out?

Ok, now I really know that I've got to dig up a copy of the C++ standards (both 1998 and 2003) and run a personal sanity check or C++ has finally succeeded in shocking me. Tested each of these with g++ 4.2.1 using the -std=c++98 -pedantic switches for the sake of quickness.

    int f=true;
    bool b=15; // 15 is demoted to 1
    enum foo_t { ONE,TWO };
    enum foo_t spam=ONE;    // ok
    enum foo_t ham=false;    // error
    enum foo_t eggs=1;   // error

In C the enum would be little better then making a pair of preprocessor defines for 0 and 1 and 'foo_t' being much like an equivalent to a typedef to one of the common integer types. In C++ enums create new types, that's nice because it actually forces you to use one of the enum values, making the last line of the example (assigning a foo_t an int) becomes an error in C++ rather then (likely) a typo in C.

That makes good sense to me and I like it, ok.

Most C implementations that I've seen that have a stdbool.h usually settles things as defining bool as an int either via reliance on typedef or the preprocessor, then defines true/false as 1/0. So there is really nothing to enforce a bool to equal anything else in common C, although I've never seen an undesired result... But in C++, bool is done as a fundamental type.... not an afterthought. So the thing I don't understand is why restrict newly created enumerations to there sane values, shooting off a compiler error if something odd happens. But allow the built in booleans to be 'almost' automatically converted like regular numerics? (apparently similar to the usual promotion/demotion rules)

bool isSomething = false; // becomes 0
isSomething++; // becomes 1
isSomething -= 500; // strangely becomes 1
isSomething--; // is an error using this operator
isSomething = isSomething -1; // becomes 0

I find it rather odd that things seem to work this way, the only logical reason I could see for it is compatibility with those in a '#define true 1' world. Personally I don't have a problem with it, I just find it odd. Maybe if I nabbed a copy of the C++ standard it would make more sense. I'm familiar enough with reading the C standard (and enjoy it) but I've never managed to get a copy of the relevant C++ standards :\. Heh, then again until recent months I haven't really touched C++ in ages... But it has been encroaching on things I normally use C or Perl for doing.

Or maybe I just need some damn __SLEEP__

No comments:

Post a Comment