473,761 Members | 4,739 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

To const or to enum?

Any opinions or comments on the following? I don't say it below, but I came
out on the side of using enumerations over static constants.

/* I'm trying to figure out the pros and cons of using static const
* int class members as opposed to using enumerations to accomplish a
* similar goal. The use of static constants seems more explicit and
* obvious to me. Unless I assign values to the enumerators, the
* compiler will do it for me. This has the advantage of saving
* keystrokes and digital ink. It has the disadvantage that I have to
* calculate the actual numerical value if I want to know what it
* is. With static constants, it is right there poking you in the eye.
*
* Enumerations support a rudimentary form of type checking. It may be
* useful, but possibly also deceptive. Basically any value that fits
* in the storage location used by the compiler to hold the
* enumerators will convert to the enumeration type, even if it is not
* a value of any of the enumerators. That can be useful for bounding
* a range of values, but it may also lead to a false impression that
* you are using a 'type-safe' value.
*
* The type checking can keep me honest if I want to be. That is, if
* I use the type name as an indicator that a given parameter is
* intended to be of that enumeration type, I can use the enumerators
* by name without explicit type conversions of the form Type(val).
*
* An example of where public static integral constants are used is in
* the w3c DOM recommendations . They serve as a form of poor-man's
* type checking. Each node type is assigned an integral constant
* value with an associated name. The base type of all nodes holds the
* definitions of these constants, and each derived node is assigned
* a named constant identical to one of those named in the baseclass.
*
* A purist may argue that static_cast, or dynamic_cast should be used
* instead, but static_cast only works for types known at compile
* time, and dynamic_cast incurs overhead beyond that of using a
* statically bound integral constant. I may be incorrect regarding
* this last point, but I'm pretty sure of it.
*
*
*/

/*
http://xml.apache.org/xerces-c/Apach...BindingL2.html
*/

/*
DOMNode.hpp:
class DOMNode
{
public:
enum NodeType {
ELEMENT_NODE = 1,
ATTRIBUTE_NODE = 2,
TEXT_NODE = 3,
CDATA_SECTION_N ODE = 4,
ENTITY_REFERENC E_NODE = 5,
ENTITY_NODE = 6,
PROCESSING_INST RUCTION_NODE = 7,
COMMENT_NODE = 8,
DOCUMENT_NODE = 9,
DOCUMENT_TYPE_N ODE = 10,
DOCUMENT_FRAGME NT_NODE = 11,
NOTATION_NODE = 12,
};
*/

/*
* The following is code I created to test certan uses of const and
* enum. I'll be more than happy to see alternatives, or additional
* uses of these syntactic elements.
*/
#include <iostream>
class A {
public:

/*
* We can't use A::EA or A::x before they are declared.
* Therefore the constructor is placed after the declarations,
* which are, in the case, definitions.
*/
/*
A(const A::AE& ae=A::x )
{
if(ae > x)
{
std::cout << "ae > x \n";
}
}
*/

/* Concise, but ugly.*/
/*
static const int X=0,
Y=1,
Z=2;
*/

/* More verbose, but clearer */
static const int X=0;
static const int Y=1;
static const int Z=2;

/* More concise, but more obscure to the untrained eye.*/
enum AE {x,y,z};

/* Placed after declarations (definitions) so I can use them*/
A(const A::AE& ae=A::x )
{
if(ae > x)
{
std::cout << "ae > x \n";
}
}

void f(const AE& ae)
{
if(ae > x)
{
std::cout << "ae > x \n";
}
}

/* How to make a DOM to XML generator, or syntax checker.*/
void g(const AE& ae)
{
switch(ae)
{
case A::x: std::cout << "case A::x \n";
return;
case A::y: std::cout << "case A::y \n";
return;
case A::z: std::cout << "case A::z \n";
return;
}
}

void h(const AE& ae)
{
switch(ae)
{
case A::x: std::cout << "case A::x \n";
return;
case A::y: std::cout << "case A::y \n";
return;
case A::z: std::cout << "case A::z \n";
return;
}
}
};

void i(const A::AE& ae)
{
switch(ae)
{
case A::x: std::cout << "case A::x \n";
return;
case A::y: std::cout << "case A::y \n";
return;
case A::z: std::cout << "case A::z \n";
return;
}
}

int main()
{
A a;
a.f(A::x);
a.f(A::AE(A::Z) );
a.f(A::AE(5));
}

--
STH
Hatton's Law: "There is only One inviolable Law"
KDevelop: http://www.kdevelop.org SuSE: http://www.suse.com
Mozilla: http://www.mozilla.org
Jul 22 '05
12 3426

"Niels Dekker - no reply address" <un*****@this.i s.invalid> wrote in message
news:41******** *******@this.is .invalid...
Conrad Weyns wrote:

Here is what I try to adhere to when using enums:

1. Prefix every enum member with the enum name unless the enum
is part of a class in which case it "can" be left out:

enum EColorType
{
EColTypeInvalid ,
EColTypeRed,
EColTypeBlue
};

Your prefix "EColType" differs from the enum name, but I guess that's a
typo...?


Indeed! It's a good job I am not anyone's compiler... :-)

Still, shouldn't we use a little namespace instead? Like
this:

namespace Color
{
enum Type
{
Invalid,
Red,
Blue
};
};

Several years ago I did it this way. These days, if it makes sense to
"group" enums I use a class instead of a namespace.
Namespaces tend to leak into header files, even precompiled headers.
Particularly when they contain entities that are "global" in nature.
I find that the use of :: in code quickly becomes an eye catcher.
EColorRed is unambiguous compared to Color::Red
A matter of code convention in the end, no big deal realy :-)
Regards,
Conrad Weyns

Regards,

Niels Dekker
www.xs4all.nl/~nd/dekkerware

Jul 22 '05 #11
"Conrad Weyns" <we***@online.n o> wrote in message
news:NY******** **********@news 4.e.nsc.no...
<snip>
2. Never ever cast an enum member.
Allways provide a complete (however large) switch to map enum
members to and from other context appropriate values.
This mapping is vital because this is the place where published
values (as read from and written to a data base) are maintained and
de-coupled from the enum.

3. Never ever use enum members in loop indexes and loop limits.


I'd feel free to break either of those two rules if the only place they are
broken is in the component that declares the enum. I've even written a
light wrapper around an enum to make it a little more user-friendly, and
inside of it, both of those rules were broken. I figure it's OK as long as
I'm not chasing down loops and casts in various unrelated modules. It may
be harder to take this approach if it will create dependency issues (e.g.
the database layer must have a mapping for an enum that it did not declare,
or another component needs to map to a DB-related enum), but it still might
be possible to work something out.

--
David Hilsee
Jul 22 '05 #12
David Hilsee wrote:
Well, I meant that as a joke to poke fun at those who might find enums
strange or mildly confusing, but I am surprised that you would say that
enums without explicitly specified values are not immediately
recognizable. I learned about enums when I first learned C, I have never
had to think
twice about them since then. To me, it is immediately recognizable,
easily understandable, and very familiar, even though I do not often use
enums or
see them used in practice. I guess I just found them very intuitive and
simple.


It depends on the situation. If it is simply a question of recognizing that
the symbold in the enum are enumerators, they there should be little
problem. If you are looking through code to find where thefollowing
definitions form the IDE are bound in C++, and what their values are, I
believe listing them as static const (or at least with explicit value
assignments for each enumerator) will be more immediately obvious than the
alternative shown below.

const unsigned short INDEX_SIZE_ERR = 1;
const unsigned short DOMSTRING_SIZE_ ERR = 2;
const unsigned short HIERARCHY_REQUE ST_ERR = 3;
const unsigned short WRONG_DOCUMENT_ ERR = 4;
const unsigned short INVALID_CHARACT ER_ERR = 5;
const unsigned short NO_DATA_ALLOWED _ERR = 6;
const unsigned short NO_MODIFICATION _ALLOWED_ERR = 7;
const unsigned short NOT_FOUND_ERR = 8;
const unsigned short NOT_SUPPORTED_E RR = 9;
const unsigned short INUSE_ATTRIBUTE _ERR = 10;
// Introduced in DOM Level 2:
const unsigned short INVALID_STATE_E RR = 11;
// Introduced in DOM Level 2:
const unsigned short SYNTAX_ERR = 12;
// Introduced in DOM Level 2:
const unsigned short INVALID_MODIFIC ATION_ERR = 13;
// Introduced in DOM Level 2:
const unsigned short NAMESPACE_ERR = 14;
// Introduced in DOM Level 2:
const unsigned short INVALID_ACCESS_ ERR = 15;
// Introduced in DOM Level 3:
const unsigned short VALIDATION_ERR = 16;
// Introduced in DOM Level 3:
const unsigned short TYPE_MISMATCH_E RR = 17;

This form is far less immediately obvious than the IDL definition:
enum{
INDEX_SIZE_ERR = 1, DOMSTRING_SIZE_ ERR, HIERARCHY_REQUE ST_ERR,
WRONG_DOCUMENT_ ERR,
INVALID_CHARACT ER_ERR, NO_DATA_ALLOWED _ERR, NO_MODIFICATION _ALLOWED_ERR,
NOT_FOUND_ERR, NOT_SUPPORTED_E RR, INUSE_ATTRIBUTE _ERR, INVALID_STATE_E RR,
SYNTAX_ERR, INVALID_MODIFIC ATION_ERR, NAMESPACE_ERR, INVALID_ACCESS_ ERR,
VALIDATION_ERR, TYPE_MISMATCH_E RR
}

Even this form is less expressive, though logically (practically) identical
to the IDL:
enum{
INDEX_SIZE_ERR = 1,
DOMSTRING_SIZE_ ERR,
HIERARCHY_REQUE ST_ERR,
WRONG_DOCUMENT_ ERR,
INVALID_CHARACT ER_ERR,
NO_DATA_ALLOWED _ERR,
NO_MODIFICATION _ALLOWED_ERR,
NOT_FOUND_ERR,
NOT_SUPPORTED_E RR,
INUSE_ATTRIBUTE _ERR,
INVALID_STATE_E RR,
SYNTAX_ERR,
INVALID_MODIFIC ATION_ERR,
NAMESPACE_ERR,
INVALID_ACCESS_ ERR,
VALIDATION_ERR,
TYPE_MISMATCH_E RR
}

--
STH
Hatton's Law: "There is only One inviolable Law"
KDevelop: http://www.kdevelop.org SuSE: http://www.suse.com
Mozilla: http://www.mozilla.org
Jul 22 '05 #13

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

7
1937
by: mcdonamw | last post by:
This may sound like a stupid stupid question and I figure it would b more "general" than pertaining to a specific Language. I'm using vb.net and I have a bunch of Const values in my program. can use them obviously by placing their names in place of values, henc the ideal behind using Const. My question is... is there a way to get the actual Variable name for specific value that is returned to me?
3
12370
by: Ajax Chelsea | last post by:
can not the "static const int" be replaced by "static enum" anywhere? is it necessary that define special initialization syntax for "static const int"?
2
1701
by: WindAndWaves | last post by:
Can anyone tell me when to use ENUM and when to use Public Const? TIA - Nicolaas
2
4081
by: shawn | last post by:
As far as i know, keyword "const" is invented to replace "define" identifier. But ... test1.c ------------------------------ #include <stdio.h> #include <stdlib.h> int main(int argc, char **argv) {
6
1502
by: shawn | last post by:
test1.c ------------------------------ #include <stdio.h> #include <stdlib.h> int main(int argc, char **argv) { const int MAX_CHAR_NUM=10; char name="Computer"; printf("My name is %s.\n", name);
7
7008
by: Peng Yu | last post by:
I'm not very clear about when to use #define and when to use const? #define number 4 const int number = 4; If I just want to define a global constant, which way of the above is better? Thanks, Peng
4
21710
by: Bilgehan.Balban | last post by:
Hi, The following code: #include <stdio.h> // const int const_asize = 10; #define define_asize = 10; int array = {1,2,3,4,5,6,7,8,9,0};
11
1796
by: Szabolcs Nagy | last post by:
is there a reason why const is not compile-time constant? the usual example, where it'd be nice is array declaration: const int N = 4; float arr or one may want to use an enum for indices: enum index {a,b,c,d,N}; float arr
16
1924
by: arnuld | last post by:
I have declared an int as const but compiler still says that it is not a const: include <stdio.h> #include <stdlib.h> int main() { const int MAXSIZE = 100;
0
9554
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10136
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
9925
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9811
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8814
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5266
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5405
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3913
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
3509
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.