Path: utzoo!utgpu!jarvis.csri.toronto.edu!mailrus!umich!samsung!cs.utexas.edu!yale!cmcl2!rna!kc From: kc@rna.UUCP (Kaare Christian) Newsgroups: comp.lang.c++ Subject: Re: const enums -- Lawyers opinions?? Summary: Yes, but typedefs aren't a new type... Keywords: const, enum Message-ID: <968@rna.UUCP> Date: 10 Jan 90 15:54:47 GMT References: <963@rna.UUCP> <10197@microsoft.UUCP> Organization: Rockefeller University - Neurobiology Lines: 58 Regarding my const enums query, I originally ran into the problem while programming an AM9513 counter timer chip. It has several registers, and I wanted to make sure that I only stuffed the appropriate bit patterns into each register. C++ 2.0's stronger enum typing (no automatic conversion of int to enum) made it possible for me to create safe set of subroutines for programming the chip. For example, I made a MasterMode enum type containing all the bit fields of the am9513 master mode register, and I made a WriteMasterMode function that only accepted a MasterMode argument. That all worked great. The only hitch is that, to create a value for, say, the master mode register, I had to OR together several of the MasterMode enum constants. I was aware that ORing enums together was likely to trigger an automatic conversion to int, and possibly a warning when that was converted back to the original enum type. What I found surprising was that I couldn't get this to work when const entered the picture. My motivation for const was to continue to have the type safety while avoiding the penalty of consuming a storage location for each of my predefined bitpatterns. Isn't that one of the main reasons for const global data types? In article <10197@microsoft.UUCP>, jimad@microsoft.UUCP (JAMES ADCOCK) writes: > > The following slight change makes more sense to me, and compiles under cfront > 2.0 without warning: > > enum bit { .... }; > > typedef int bits; > > ... > > bits someresult = one | two | whatever; > I'm aware of the technique, but it doesn't let me use type checking to avoid putting a countermode value into a mastermode register. > [not to imply bit or bits are good names to use for these things, nor > zero, one, two, ...] Yup, bad names in general, it was just the smallest example I could devise. I guess that a better solution than what I showed before is the following: bits x = (bits)(one | two); const bits y = (const bits)(one | two); This coerces the expr result back to what I want, and looks more reasonable. But in general, the 2.0 tightening of the enum type rules seems not tight enough. Arithmetic operations on enums promote to int, thereby losing the typing. Why not have arithmetic operations on enums *act* as int operations, but retain typing? One could only do binop stuff on enums of the same type (unless explicit casts were used), and enum op enum would always produce an enum type. In hindsight, I think I should have used a classier solution (pun intended) or bitfields. Kaare Christian