473,799 Members | 3,080 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

C-style casts for built-in types?

Hi,

I am maintaining a lot of code that is rife with C-style casts. I've
seen a lot of comments that one should not use C-style casts at all. But
I'm wondering what harm there could be in doing so with the built-in types.
For example, if you have a long which needs to be passed to a function as an
unsigned long, or a char* that needs to be passed as an unsigned char*, or
an unsigned int that needs to be passed as a long, isn't it perfectly safe
to use C-style casts just to avoid compilation problems? When we make
release builds, we generally treat warnings as errors, so there's a lot of
casting going on, and it's a lot less typing to say, for example, (given an
unsigned char* aName): (char*)aName than it is to say
static_cast<cha r*>(aName). One's 12 characters, the other's 25! That's a
lot of extra work, and what for, exactly? What could go wrong with the
C-style cast in simple cases like this? I know reasons for when I'm dealing
with classes, unrelated pointer types, etc., but what about the simple
built-in types...is there *really* any difference?

Thanks,
-Howard

Jul 22 '05 #1
3 1473
Howard wrote:
I am maintaining a lot of code that is rife with C-style casts. I've
seen a lot of comments that one should not use C-style casts at all. But
I'm wondering what harm there could be in doing so with the built-in types.
For example, if you have a long which needs to be passed to a function as an
unsigned long, or a char* that needs to be passed as an unsigned char*, or
an unsigned int that needs to be passed as a long, isn't it perfectly safe
to use C-style casts just to avoid compilation problems? When we make
release builds, we generally treat warnings as errors, so there's a lot of
casting going on, and it's a lot less typing to say, for example, (given an
unsigned char* aName): (char*)aName than it is to say
static_cast<cha r*>(aName). One's 12 characters, the other's 25! That's a
lot of extra work, and what for, exactly? What could go wrong with the
C-style cast in simple cases like this? I know reasons for when I'm dealing
with classes, unrelated pointer types, etc., but what about the simple
built-in types...is there *really* any difference?


char, unsigned char, signed char, are all the same size and there is
probably no harm in casting one to another. There are, however, some
cases where the result is, well, questionable. What if you have 128
in an unsigned char and try to convert it to a signed char? The latter
cannot represent 128 (usually). What do you have? Implementation-
defined behaviour. IOW, it's not portable because it's may be
different with another compiler. Can you rely on those?

Unsigned int and long _can_ be of the same size. The same problem
exists when converting between those types -- if the unsigned int has
a value that cannot be represented in the long, the behaviour is set
by the implementation and not necessarily the same for all of them.

Now, if you can make sure that all you do is cast between "congenial"
types, then no big deal, use C-style casts. Hell, nobody can tell you
not to use them, it's your system, you're the maintainer, why should
we care? But the whole hoopla about them is based on the premise that
(a) sometimes you can't make sure and (b) it breeds a bad habit.

I'd say, if your primary concern is for wearing out your fingertips
while typing too much, your system is waaaay too simple or its life
span is waaaay too short to talk about.

V
Jul 22 '05 #2

"Howard" <al*****@hotmai l.com> wrote in message
news:T2******** ************@bg tnsc04-news.ops.worldn et.att.net...
Hi,

I am maintaining a lot of code that is rife with C-style casts. I've
seen a lot of comments that one should not use C-style casts at all. But
I'm wondering what harm there could be in doing so with the built-in types. For example, if you have a long which needs to be passed to a function as an unsigned long, or a char* that needs to be passed as an unsigned char*, or
an unsigned int that needs to be passed as a long, isn't it perfectly safe
to use C-style casts just to avoid compilation problems? When we make
release builds, we generally treat warnings as errors, so there's a lot of
casting going on, and it's a lot less typing to say, for example, (given an unsigned char* aName): (char*)aName than it is to say
static_cast<cha r*>(aName). One's 12 characters, the other's 25! That's a
lot of extra work, and what for, exactly? What could go wrong with the
C-style cast in simple cases like this? I know reasons for when I'm dealing with classes, unrelated pointer types, etc., but what about the simple
built-in types...is there *really* any difference?


I think the main problem arises when you change the types in your program.
When you change types what had been a benign cast can suddenly become
dangerous. With C style casts you get no warning, the cast will happen
anyway. With C++ style casts you get a bit more insurance.

john
Jul 22 '05 #3
"Howard" <al*****@hotmai l.com> wrote in message news:T2wLc.2963 07
I am maintaining a lot of code that is rife with C-style casts. I've
seen a lot of comments that one should not use C-style casts at all. But
I'm wondering what harm there could be in doing so with the built-in types. For example, if you have a long which needs to be passed to a function as an unsigned long, or a char* that needs to be passed as an unsigned char*, or
an unsigned int that needs to be passed as a long, isn't it perfectly safe
to use C-style casts just to avoid compilation problems? When we make
release builds, we generally treat warnings as errors, so there's a lot of
casting going on, and it's a lot less typing to say, for example, (given an unsigned char* aName): (char*)aName than it is to say
static_cast<cha r*>(aName). One's 12 characters, the other's 25! That's a
lot of extra work, and what for, exactly? What could go wrong with the
C-style cast in simple cases like this? I know reasons for when I'm dealing with classes, unrelated pointer types, etc., but what about the simple
built-in types...is there *really* any difference?


To me, C style casts are fine for any value types: if you have a long which
needs to be passed to a function as an unsigned long, or an unsigned int
that needs to be passed as a long. The C++ casts are generally only for
pointer and reference types: if you have a char* that needs to be passed as
an unsigned char* for which I'd use reinterpret_cas t. Use const_cast to
cast away const or reference or pointer types, or in rare cases to add 2nd
level const. Use static_cast to cast from base to derived class, and
various other tasks. Use reinterpret_cas t for the rest. The C++ style
casts stand out well and code reviews, and can be searched for by your IDE
or editor.
Jul 22 '05 #4

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

Similar topics

0
1176
by: Pete Shinners | last post by:
I've been spending the last few night upgrading some 'classic' type objects to the more modern 'newstyle' types. Unless I am not finding some important page, this entire process is almost entirely undocumented. I've found the "Noddy" example, which was a helping start. But Noddy only gets you halfway there, and where it leaves off there is no further assistance. I've been using the builtin Python types source as example, but this isn't...
2
5163
by: BJörn Lindqvist | last post by:
A problem I have occured recently is that I want to subclass builtin types. Especially subclassing list is very troublesome to me. But I can't find the right syntax to use. Take for example this class which is supposed to be a representation of a genome: class Genome(list): def __init__(self): list.__init__(self) self = ....
11
4393
by: Shaun | last post by:
Hi, I'm trying to overload the divide operator in python for basic arithmetic. eg. 10/2 ... no classes involved. I am attempting to redefine operator.__div__ as follows: # my divide function def safediv(a,b): return ...
9
1807
by: Steph | last post by:
Hello, I am searching for the best way to get all base types in framework (int, string, float...). Any idea ? Thanks
17
1213
by: Fabiano Sidler | last post by:
Hi folks! For debugging purposes I tried this: --- snip --- def foo(): pass function = type(foo) class PrintingFunction(function): def __init__(self, func):
6
1469
by: gangesmaster | last post by:
let's start with a question: ========== >>> class z(object): .... def __init__(self): .... self.blah=5 .... >>> class x(object): .... def __init__(self): .... z.__init__(self)
0
1675
by: nejucomo | last post by:
Hi folks, Quick Synopsis: A test script demonstrates a memory leak when I use pythonic extensions of my builtin types, but if I use the builtin types themselves there is no memory leak. If you are interested in how builtin/pure-python inheritance interacts
20
2136
by: Ari Krupnik | last post by:
scripts can add methods to the prototypes of builtin objects in JaavScript. I can assign functions to String.prototype.*, for instance. I want to add a method to Node, but when I try to execute the following IE says "'Node' is undefined." Mozilla works as I expected it to. Is Node called something else in IE? Does IE not allow manipulating the prototypes of some builtin objects? Node.prototype.nt = function() { return this.nodeType; }
6
2562
by: =?iso-8859-1?q?Erik_Wikstr=F6m?= | last post by:
Is there some way to get a function-pointer to the operators of the builtin types? In the following example I have a generic function which applies an operator on two values, however it does not work on builtin types, is there a way to make this work? struct Test { int i; Test(int i_) : i(i_) { } Test operator+(Test& t) { return Test(i + t.i); }
55
3999
by: tonytech08 | last post by:
How valuable is it that class objects behave like built-in types? I appears that the whole "constructor doesn't return a value because they are called by the compiler" thing is to enable built-in-like behavior for objects of class type. That leads to the "necessity" for the exception machinery so that errors from constructors can be handled. Is all that complexity worth it just to get built-in-like behavior from class objects? Maybe a...
0
9687
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
10484
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
10027
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
9072
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
7565
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
6805
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5463
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...
1
4141
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
2
3759
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.