473,695 Members | 1,731 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

enums in C and C++

I'm porting thousands of lines of legacy C code to C++. One makor issue
I've got is that of enums being treated differently in C and C++.
There's an automatic cast from int to enum in C but not in C++. The
code is full of constructs like this:

enum { CARROT=0x01,TUR NIP=0x02,PARSNI P=0x04,SPROUT=0 x08 } garden_veg;

garden_veg = CARROT|PARSNIP; /* Fine in C, but not in C++ */

Do I really have to trawl through all this code and put in many
hundreds of casts, or is there something clever I can do to get round
this?

--
Simon Elliott http://www.ctsn.co.uk
Jul 22 '05 #1
9 1525
Simon Elliott wrote:
I'm porting thousands of lines of legacy C code to C++. One makor issue
I've got is that of enums being treated differently in C and C++.
There's an automatic cast from int to enum in C but not in C++. The
code is full of constructs like this:

enum { CARROT=0x01,TUR NIP=0x02,PARSNI P=0x04,SPROUT=0 x08 } garden_veg;

garden_veg = CARROT|PARSNIP; /* Fine in C, but not in C++ */

Do I really have to trawl through all this code and put in many
hundreds of casts, or is there something clever I can do to get round
this?


The only "clever" thing to do is to keep this C (if it worked before, why
change?)

V
Jul 22 '05 #2
Simon Elliott wrote:
I'm porting thousands of lines of legacy C code to C++. One makor issue
I've got is that of enums being treated differently in C and C++.
There's an automatic cast from int to enum in C but not in C++. The
code is full of constructs like this:

enum { CARROT=0x01,TUR NIP=0x02,PARSNI P=0x04,SPROUT=0 x08 } garden_veg;

garden_veg = CARROT|PARSNIP; /* Fine in C, but not in C++ */

Do I really have to trawl through all this code and put in many
hundreds of casts, or is there something clever I can do to get round
this?

Why are you bothering to port C code to C++?* Leave it in C and call
what you need (from C++).

HTH,
--ag

* - No slam on C++ intended; just a practical comment.

--
Artie Gold -- Austin, Texas

"If you don't think it matters, you're not paying attention."
Jul 22 '05 #3
Thierry Miceli posted:
enum { CARROT=0x01,TUR NIP=0x02,PARSNI P=0x04,SPROUT=0 x08 } garden_veg;

garden_veg = CARROT|PARSNIP; /* Fine in C, but not in C++ */

Do I really have to trawl through all this code and put in many
hundreds of casts, or is there something clever I can do to get round
this?
If you really want to convert the code to C++ you could try to

redefine the '|' operator for the enum. e.g:

enum GardenVegetable s {
CARROT=0x01,TUR NIP=0x02,PARSNI P=0x04,SPROUT=0 x08 };

GardenVegetable s operator|(Garde nVegetables veg1, GardenVegetable s
veg2) {
return (GardenVegetabl es) ((int)veg1 | (int)veg2);
}

return static_cast<Gar denVegetables>( ( static_cast<int >(veg1) |
static_cast<int >(veg2) ) );
C++, not C/C++ ;-D
-JKop

Jul 22 '05 #4
"JKop" <NU**@NULL.NULL > wrote in message news:Pyngd.4034 8
Thierry Miceli posted:

enum GardenVegetable s {
CARROT=0x01,TUR NIP=0x02,PARSNI P=0x04,SPROUT=0 x08 };

GardenVegetable s operator|(Garde nVegetables veg1, GardenVegetable s
veg2) {
return (GardenVegetabl es) ((int)veg1 | (int)veg2);
}

return static_cast<Gar denVegetables>( ( static_cast<int >(veg1) |
static_cast<int >(veg2) ) );
C++, not C/C++ ;-D


It seems fine to use C style casts for converting one integer/float type to
another. Imagine that there exists a constructor
GardenVegetable s::GardenVegeta bles(int). Only for converting one
pointer/reference type to another do I use one of the C++ style casts
(usually static_cast, but sometimes reinterpret_cas t).

Also, instead of
return (GardenVegetabl es) ((int)veg1 | (int)veg2);


one could say

return GardenVegetable s ( (int(veg1) | int(veg2)) );

but neither way is superior, though I'm not sure if this second way is
allowed in C.
Similarly, "(size_t)i" which is equivalent to "size_t(i)" where i is an int,
also seems fine to me as a good style of C++.
Jul 22 '05 #5
Similarly, "(size_t)i" which is equivalent to "size_t(i)" where i is an int, also seems fine to me as a good style of C++.

See but that's why "reinterpret_ca st" was given such a horrid name:
float p;

int* k = (int*) &p; //legal

int* k = int*(&p) ; // no can do
To achieve this, you need to be horrid:

int* k = reinterpret_cas t<int* const>(&p);
I myself never use (int). Here's how I do it:

Step 1) Use "static_cas t". If rejected go to step 2.

Step 2) Use "reinterpret_ca st".
I've never had to use "dynamic_ca st" so far!
-JKop
-JKop
Jul 22 '05 #6
> > GardenVegetable s operator|(Garde nVegetables veg1, GardenVegetable s
veg2) {
return (GardenVegetabl es) ((int)veg1 | (int)veg2);
}

return static_cast<Gar denVegetables>( ( static_cast<int >(veg1) |
static_cast<int >(veg2) ) );
C++, not C/C++ ;-D

I agree, I sacrificed purity for readability.

Thierry
Jul 22 '05 #7
"JKop" <NU**@NULL.NULL > wrote in message news:M7pgd.4039 7
Similarly, "(size_t)i" which is equivalent to "size_t(i)" where i is an
int, also seems fine to me as a good style of C++.

See but that's why "reinterpret_ca st" was given such a horrid name:
float p;

int* k = (int*) &p; //legal

int* k = int*(&p) ; // no can do


I agree that for casting between pointer and reference types, it's good to
use static_cast or reinterpret_cas t. But for casting between value types, C
style casts which behave like constructors, seem perfectly fine.

To achieve this, you need to be horrid:

int* k = reinterpret_cas t<int* const>(&p);
I myself never use (int). Here's how I do it:

Step 1) Use "static_cas t". If rejected go to step 2.

Step 2) Use "reinterpret_ca st".
Agreed for pointer types only.
I've never had to use "dynamic_ca st" so far!


It arises when writing generic code, and you can't or don't want to edit the
base class by continually adding virtual functions to it.
Jul 22 '05 #8
Siemel Naran wrote:
I agree that for casting between pointer and reference types, it's good to
use static_cast or reinterpret_cas t. But for casting between value types, C
style casts which behave like constructors, seem perfectly fine.

C++ newer casts are still better.


--
Ioannis Vranos

http://www23.brinkster.com/noicys
Jul 22 '05 #9
On 28/10/2004, Simon Elliott wrote:
[snip]

Thanks for all the responses to this. I'm still unsure about how to
proceed because there are lots of different enums which are used in
lots of different ways. With the current compiler (BCB3) I have the
(slightly grubby) option of suppressing the warning and leaving
everything as it is. But it's possible that other compilers won't let
me do this.

--
Simon Elliott http://www.ctsn.co.uk
Jul 22 '05 #10

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

Similar topics

13
9547
by: SpaceCowboy | last post by:
I recently got into a discussion with a co-worker about using enums across a dll interface. He wanted to use chars instead, argueing that depending on compiler settings the size of an enum could change and lead to memory corruption. I didn't see how this was possible. He claims that if a dll built for a program is built with different compiler settings than the launcher program, the enum size could change. The only way I could figure...
2
2075
by: Faisal | last post by:
Can anyone tell me if it is possible to enumerate through all the Enums within a class . I have a class with many Enums and would like to accees the Enums through an array/collection etc. I can't seem to find an appropriate Reflection method to access Enums within a class I would like to loop through the Enums in the 'Foo' Class retrieve the Enums 'Car' and 'House Public Class Fo Public Enum Ca For Chevrole Toyot
27
2727
by: Mark A. Gibbs | last post by:
i have been toying with the idea of making my enums smarter - ie, more in line with the rest of the language. i haven't tested it yet, but what i came up with is a template like this: template <typename Enum> class smart_enum { public: typedef Enum enum_type;
2
1790
by: SpotNet | last post by:
Hello CSharpies, Can Enums in C# be UInt32 Types, and not just Int32 Types. I have a lot of constant declarations that are UInt32 that I want to put in Enums to ease the use of Intellisence. I have them in structs for now, I thought I'd ask. Would IntPtr Enums push the bounds of a stupid question? Regarding a post a bit further down by Tom; ' What would you like to change in C# and .NET?'
4
5589
by: Martin Pritchard | last post by:
Hi, I'm working on a project that historically contains around 40 enums. In the database various fields refer to the int values of these enums, but of course ref integrity is not enofrced and when looking at the db we can't tell what the value in a field represents. The other problem is that our enums are currently all stored in a single class, which means that because of no visibility constraints the enums are often used out of context...
2
1991
by: Faisal | last post by:
Can anyone tell me if it is possible to enumerate through all the Enums within a class . I have a class with many Enums and would like to accees the Enums through an array/collection etc. I can't seem to find an appropriate Reflection method to access Enums within a class Thanks! --- Posted using Wimdows.net Newsgroups - http://www.wimdows.net/newsgroups/
2
2879
by: Simon Elliott | last post by:
I have some legacy C++ code which requires some enums to be 1 or 2 bytes in size. I'd ideally like to be able to specify that a few carefully selected enums are a particular size. By default, g++ seems to create enums of 4 bytes in length, unless I use the -fshort-enums option. I don't much want to use this all or nothing approach in case it breaks library code etc, and there's no guarantee that other compilers have a comparable...
11
12508
by: Marc Gravell | last post by:
This one stumped me while refactoring some code to use generics... Suppose I declare an enum MyEnum {...} Is there a good reason why MyEnum doesn't implement IEquatable<MyEnum> ? Of course, I can cast a MyEnum instance down to the int / short whatever (since int implements IEquatable<int>), but I don't like doing that, as it feels a bit messy, and I am then propegating the things that know what the base represenation is...
4
2995
by: Jon Slaughter | last post by:
is there a simple way to "step" through enums? I have a button that I want to click and have it "cycle" through a set of states defined by enums but the only way I can think of doing this "properly" yet "ugly" is to test the state for each state. I know that enumes are not ordered but since they are "stored" as numbers they have an inherent ordering which can be used. I don't really care about the ordering though but just the ability to...
13
5003
by: Bob | last post by:
Hi, Can someone explain why you can't declare enums in an interface? The compiler says "interfaces can't declare types" Ignoring the syntax implications it seems to me that you should be able to declare that an enum exists. i.e. It is within the 'spirit' of an interface to state that it exists. The implementing class will provide the members. e.g. I have a code library that performs a function. It exposes two interfaces which allow for...
0
8652
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
9140
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...
0
9005
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8841
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
7688
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...
1
6511
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4351
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...
2
2291
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
1987
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.