I have the following:
1: template< class Sumtype, class Averagetype >
2: Averagetype Average( Sumtype* p_array, Averagetype p_count )
3: {
4: int index;
5: Sumtype sum = 0;
6: for( index = 0; p_count index; index++ )
7: sum += p_array[index];
8: return (Averagetype)sum / p_count;
9: }
It's from a book that I am currently reading.
I'm curious to know what the standard says
about the cast to Averagetype?
--
conrad 11 1506
conrad wrote:
I have the following:
1: template< class Sumtype, class Averagetype >
2: Averagetype Average( Sumtype* p_array, Averagetype p_count )
3: {
4: int index;
5: Sumtype sum = 0;
6: for( index = 0; p_count index; index++ )
7: sum += p_array[index];
8: return (Averagetype)sum / p_count;
9: }
It's from a book that I am currently reading.
I'm curious to know what the standard says
about the cast to Averagetype?
Nothing. There is no mention of 'Averagetype' in the Standard.
On the serious note, what do you expect the Standard to say?
C-style casts are part of the language, they usually end up
being static_cast or const_cast or reinterpret_cast or some
kind of combination of both, or, sometimes, something else
that none of standard C++ casts support. In your case the
cast is probably static_cast.
V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
conrad wrote:
1: template< class Sumtype, class Averagetype >
2: Averagetype Average( Sumtype* p_array, Averagetype p_count )
3: {
....
8: return (Averagetype)sum / p_count;
9: }
It's from a book that I am currently reading.
I'm curious to know what the standard says
about the cast to Averagetype?
It calls Averagetype::Averagetype(Sumtype const & x), which must exist (to
within input type variations).
Next, it could have been written with constructor notation:
Averagetype(sum)
Or as an elaborate_cast:
static_cast<Averagetype>(sum)
Question: Which is better style?
--
Phlip
Phlip <ph******@yahoo.comwrote in message...
>
It calls Averagetype::Averagetype(Sumtype const & x), which must exist (to
within input type variations).
Next, it could have been written with constructor notation:
Averagetype(sum)
Or as an elaborate_cast:
static_cast<Averagetype>(sum)
Question: Which is better style?
The C++ cast. It is so ugly, you can't ignore it!
Better error/warnings when compiling.
Also, it makes it easy to search for with an editor.
( search (non-whole word): "_cast<", will find 'em all. Try that with a
C-style cast! )
I use the 'constructor-notation' for simple things I know are (relatively)
safe:
for( int i(0); size_t( i ) < somevector.size(); ++i ){
// some op that needs an int.
}
.... the 'size_t( i )' shuts-up the compiler warning.
--
Bob R
POVrookie
On Oct 2, 3:32 am, "BobR" <removeBadB...@worldnet.att.netwrote:
Phlip <phlip...@yahoo.comwrote in message...
[snip and agree]
for( int i(0); size_t( i ) < somevector.size(); ++i ){
// some op that needs an int.
}
... the 'size_t( i )' shuts-up the compiler warning.
Hi Bob,
I am interested to know why you use this version:
for( int i(0); size_t( i ) < somevector.size(); ++i )
....as opposed to this one:
for( size_t i(0); i < somevector.size(); ++i )
?
Isn't your version casting an int to a size_t every time
it the expression is evaluated?
Where as (please correct me if I'm wrong gang), I don't
think the latter version does?
Cheers,
Chris Val
Chris ( Val ) wrote:
On Oct 2, 3:32 am, "BobR" <removeBadB...@worldnet.att.netwrote:
>Phlip <phlip...@yahoo.comwrote in message...
[snip and agree]
>for( int i(0); size_t( i ) < somevector.size(); ++i ){ // some op that needs an int. } ... the 'size_t( i )' shuts-up the compiler warning.
Hi Bob,
I am interested to know why you use this version:
for( int i(0); size_t( i ) < somevector.size(); ++i )
...as opposed to this one:
for( size_t i(0); i < somevector.size(); ++i )
?
Isn't your version casting an int to a size_t every time
it the expression is evaluated?
Where as (please correct me if I'm wrong gang), I don't
think the latter version does?
It can be because inside the loop body 'i' is used all over the
place where an 'int' is expected (in expressions where signed
values are used, in function arguments that need 'int', etc.)
Having a 'size_t' in those places is dangerous since it can
cause other parts of the expression to be made unsigned with
results you might not want.
This is just a speculation of course.
V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Chris ( Val ) wrote in message...
On Oct 2, 3:32 am, "BobR" <removeBadB...@worldnet.att.netwrote:
[snip and agree]
for( int i(0); size_t( i ) < somevector.size(); ++i ){
// some op that needs an int.
}
... the 'size_t( i )' shuts-up the compiler warning.
Hi Bob,
I am interested to know why you use this version:
for( int i(0); size_t( i ) < somevector.size(); ++i )
...as opposed to this one:
for( size_t i(0); i < somevector.size(); ++i )
?
Isn't your version casting an int to a size_t every time
it the expression is evaluated?
Hi Chris,
Pretty much what Victor said.
My current project would require me to cast hundreds of places if I used the
'for( size_t ...)' version. So, I'd rather cast in one single place, until
I'm ready to tackle the final 23 functions [converting an old 'C' set of
programs into one 'C++' (monster!) program. Creates a 3D object out of a few
random numbers.].
Going from 'int' to 'size_t' is pretty safe (unless a really big number will
cause failure.<G>).
Use the proper type where you can, pick the lesser of two evils in other
places.
When I have a choice, I use the 'size_t', especially when dealing with an
index.
My project did use an negative index, and it took me forever to 'clean'.
struct Thing{ // the 'C' stuff I 'inherited'.
double peak;
double array[6];
};
Thing thing;
for( int i( -1 ); i < 6; ++i ){ // size_t( i) == problem here
thing.array[ i ] = someassign;
// first loop modifies 'peak'!! I HATE that.
}
Drove me nuts for a while! (made 'array' a std::vector, and kept
segfaulting.).
( yeah, I'm still nuts, but not for that construct! <G>).
My project works smooth as glass now, so I'm working on the interfaces
(separating wxWidgets from the 'workhorse', then I'll optimise the
bottlenecks (and should be able to eliminate (most of) the for loops).)
Ooops, running off-topic again. Sorry.
>
Where as (please correct me if I'm wrong gang), I don't
think the latter version does?
Not AFAIK.
Depends on the requirements/restrictions in the loop body.
[ How do you know the compiler does not optimise it? ]
--
Bob R
POVrookie
BobR wrote in message...
>
Where as (please correct me if I'm wrong gang), I don't
think the latter version does?
Not AFAIK.
Depends on the requirements/restrictions in the loop body.
Which (size_t, int) you use depends on .....
--
Bob R
POVrookie
On Oct 2, 5:09 am, "Victor Bazarov" <v.Abaza...@comAcast.netwrote:
Chris ( Val ) wrote:
On Oct 2, 3:32 am, "BobR" <removeBadB...@worldnet.att.netwrote:
Phlip <phlip...@yahoo.comwrote in message...
[snip and agree]
for( int i(0); size_t( i ) < somevector.size(); ++i ){
// some op that needs an int.
}
... the 'size_t( i )' shuts-up the compiler warning.
Hi Bob,
I am interested to know why you use this version:
for( int i(0); size_t( i ) < somevector.size(); ++i )
...as opposed to this one:
for( size_t i(0); i < somevector.size(); ++i )
?
Isn't your version casting an int to a size_t every time
it the expression is evaluated?
Where as (please correct me if I'm wrong gang), I don't
think the latter version does?
It can be because inside the loop body 'i' is used all over the
place where an 'int' is expected (in expressions where signed
values are used, in function arguments that need 'int', etc.)
Having a 'size_t' in those places is dangerous since it can
cause other parts of the expression to be made unsigned with
results you might not want.
This is just a speculation of course.
Hi Victor,
Yes. I agree, and thank you for the feedback.
The initial reason for my concern was that of efficiency,
given that the condition is cast through each iteration
of the loop.
Ideally, it is recommended that "std::vector<int>::size_type"
be used, even though it may be a size_t internally.
Cheers,
Chris Val
On Oct 2, 11:10 am, "BobR" <removeBadB...@worldnet.att.netwrote:
BobR wrote in message...
Where as (please correct me if I'm wrong gang), I don't
think the latter version does?
Not AFAIK.
Depends on the requirements/restrictions in the loop body.
Which (size_t, int) you use depends on .....
Hi Bob,
I'm not quite sure what you are getting at here?
Are you saying it is possible that the second example
I provided is or can be cast through each iteration?
I do not believe that to be the case in that context.
Cheers,
Chris Val
On Oct 2, 8:30 am, "BobR" <removeBadB...@worldnet.att.netwrote:
Chris ( Val ) wrote in message...
[snip]
Hi Bob,
Going from 'int' to 'size_t' is pretty safe (unless a really big number will
cause failure.<G>).
But an integer as small as '-1' can cause you a lot of grief :-)
Use the proper type where you can, pick the lesser of two evils in other
places.
I agree, and the main reason for my post :-)
If std::vector::size() returns an unsigned type, then
by your own laws of evil you should have used:
for( size_t i(0); i < ....; ... )
{
// ...
When I have a choice, I use the 'size_t', especially when dealing with an
index.
My project did use an negative index, and it took me forever to 'clean'.
Understandable.
struct Thing{ // the 'C' stuff I 'inherited'.
double peak;
double array[6];
};
Thing thing;
for( int i( -1 ); i < 6; ++i ){ // size_t( i) == problem here
thing.array[ i ] = someassign;
// first loop modifies 'peak'!! I HATE that.
}
[snip]
Yes, as noted above, this is where a negative integer can
really cause you a lot of grief with an unsigned type such
as size_t.
Cheers,
Chris Val
"conrad" <co****@lawyer.comwrote in message
news:11**********************@22g2000hsm.googlegro ups.com...
8: return (Averagetype)sum / p_count;
I'm curious to know what the standard says
about the cast to Averagetype?
I haven't read all the comments in this thread, but so far none of them has
noted the following:
Because a cast is essentially a unary operator, it binds more tightly than
division. Therefore,
return (Averagetype)sum / p_count;
is interpreted as
return ((Averagetype) sum) / p_count;
This characteristic is particularly important if sum has an integral type
and Averagetype has a floating-point type. In that case, the cast converts
sum to floating-point and only then divides it by p_count. This conversion,
in turn, is important because otherwise the result of the division would be
truncated to an integer.
Because this precedence subtlety is so important, and so easily missed, I
would be inclined to write the second return statement above instead of the
first. This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics
by: Tao |
last post by:
I just upgraded .NET framework to 1.1 and VS.Net to 2003 version and
tried to test it out. I created an ASP.NET project using the wizard
and tried to run
it by hitting "F5". I got an exception:...
|
by: James Aguilar |
last post by:
Someone showed me something today that I didn't understand. This doesn't
seem like it should be valid C++. Specifically, I don't understand how the
commas are accepted after the function...
|
by: Tyro |
last post by:
Can someone shed some light on my error here? Thanks!
Specified cast is not valid.
Exception Details: System.InvalidCastException: Specified cast is not
valid.
Source Error:
Stack Trace:
|
by: PK9 |
last post by:
I am looking for assistance in pinpointing the cause of the following
exception. I am getting a "Specified Cast is not valid" exception on my
page. I am trying to populate a datagrid. One of my...
|
by: Fabian |
last post by:
Hi,
I work with asp.net 2.0 and I have a intermittent error, only happens a few
times a day.
In the page I evaluate a Query String and then I get data form a database.
The code snipped:
...
|
by: VB Programmer |
last post by:
I am setting up forms authentication.
In my code I keep getting this error. Any ideas?
Error....
Server Error in '/LandOLots' Application....
|
by: QA |
last post by:
I am using a Business Scorecard Accelarator in a Sharepoint Portal 2003
using SQL Server 2005
I am getting the following error:
Error,5/7/2005 10:50:14 AM,580,AUE1\Administrator,"Specified cast is...
|
by: Alan Z. Scharf |
last post by:
this question in datagrid group for several days with no
repsonse.
I'm hoping for an answer her because of greater activity in this group.
No cross-posting intended. Thanks....
|
by: Gamma |
last post by:
I'm trying to inherit subclass from System.Diagnostics.Process, but
whenever I cast a "Process" object to it's subclass, I encounter an
exception "System.InvalidCastException" ("Specified cast is...
|
by: =?Utf-8?B?UGF1bCBQcmV3ZXR0?= |
last post by:
I'm attempting to use LINQ to insert a record into a child table and I'm
receiving a "Specified cast is not valid" error that has something to do w/
the keys involved. The stack trace is:
...
|
by: emmanuelkatto |
last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud.
Please let me know.
Thanks!
Emmanuel
|
by: BarryA |
last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
|
by: Sonnysonu |
last post by:
This is the data of csv file
1 2 3
1 2 3
1 2 3
1 2 3
2 3
2 3
3
the lengths should be different i have to store the data by column-wise with in the specific length.
suppose the i have to...
|
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,...
|
by: Hystou |
last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
|
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,...
|
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...
|
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...
|
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...
| |