473,786 Members | 2,410 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

ternary operator and casting

In the following code

//add to bool or double Dictionary
this.m_unit.Add ((unittype == "b")? unitnum:(double )unitnum);

The bool dictionary uses an integer index, the double uses a double
index, which some may take issue with, but that's a different
discussion. The problem is that unitnum is always cast to a double, even
when unittype is "b". That seems like a bug to me.

If I change it to

this.m_unit.Add ((unittype == "d")? (double)unitnum :unitnum);

it still always casts it to a double. I'm annoyed that the ternary
operator always casts unitnum to a double.

(parenthetical discussion)

The object is to later be able to set values, like so

//1234 is a bool
Grp.Unit[1234] = true;
//4321 is a double
Grp.Unit[4321d] = 1.0;
//there is also a uint index for conversion between bool and double
//set bool from double
Grp.Unit[1234u] = 1.0;
//set double from bool
double myvalue = Grp.Unit[1234u];

but, like I said, that's not the discussion I want to have. There is a
lot of code, and it minimizes it, especially when dealing with
bool-to-double conversions.

*** Sent via Developersdex http://www.developersdex.com ***
Jul 16 '08 #1
8 2118
On Jul 16, 4:22*pm, Bob Hoeppner <boba...@hotmai l.comwrote:
In the following code

//add to bool or double Dictionary
this.m_unit.Add ((unittype == "b")? unitnum:(double )unitnum);

The bool dictionary uses an integer index, the double uses a double
index, which some may take issue with, but that's a different
discussion. The problem is that unitnum is always cast to a double, even
when unittype is "b". That seems like a bug to me.
No - it's a flaw in your understanding of the conditional operator.

The conditional operator is (as you know) an expression of the form
a ? b : c. That expression is of a single type, in the end. Both the
subexpressions "b" and "c" have to be convertible to the overall type
of the expression, which (IIRC) is always either the type of b or the
type of c.

In your case, you end up with b and c being unitnum (type=int) and
(double)unitnum (type=double). int is implicitly convertible to
double, but not vice versa - so the overall type of the expression is
double. That means you always get the Add(double) overload being
called, and there is indeed always a conversion.

Assuming the Add method is overloaded (once for int and once for
double) then you need to have two different method calls to get it to
work. Any one method call will only resolve to a single overload.

Then again, it's quite strange to see an overload like that, so it's
possible that my assumptions about the type of m_unit are incorrect.
If the explanation above hasn't helped you, could you provide a short
but complete program which demonstrates the problem?

Jon
Jul 16 '08 #2
On Wed, 16 Jul 2008 08:22:32 -0700, Bob Hoeppner <bo*****@hotmai l.com
wrote:
In the following code

//add to bool or double Dictionary
this.m_unit.Add ((unittype == "b")? unitnum:(double )unitnum);

The bool dictionary uses an integer index, the double uses a double
index, which some may take issue with, but that's a different
discussion. The problem is that unitnum is always cast to a double, even
when unittype is "b". That seems like a bug to me.
It's not a bug. The type of the expression has to be determined at
compile-time, so the compiler cannot take into account possible
differences in the two possible outcomes of the operator. It has to
resolve the entire expression into a single, compile-time type. It does
this by choosing the type that both possible outcomes can be converted
to. There's no implicit conversion from double to int, but there's an
implicit conversion from int to double, so double wins.

Assuming "unitnum" is an integer variable, then I'm not clear on why
you're casting in the first place. Where the expression needs to resolve
to a double, the implicit conversion should handle that for you.

Beyond that, I'm not entirely sure that the use of a double is "a
different discussion". To some extent, this is an issue for you because
you are trying to treat two different collections as the same, so there's
at least that. The other issue is that a dictionary is going to use
equality for matching keys, but floating point values are poor candidates
for equality comparisons.

In other words, you do in fact have a potential design issue that has led
to this dilemma, and fixing that design issue may in fact cause your
immediate question to become moot.

Pete
Jul 16 '08 #3
Yes, I see my understanding was flawed. It makes sense the one ternary
operator would have to return one datatype. This demonstrates that the
ternary operator is not an exact shorthand equivalent for an if/else
statement. Thanks.

*** Sent via Developersdex http://www.developersdex.com ***
Jul 16 '08 #4
Yes, I see my understanding was flawed. It makes sense the one ternary
operator would have to return one datatype. This demonstrates that the
ternary operator is not an exact shorthand equivalent for an if/else
statement. Thanks.

Yes, I'm treating two collections as similarly as possible. There are
many bools and fewer doubles. Also, there is a lot of assigning of bools
to doubles and doubles to bools, due to the nature of the two systems
I'm interfacing. I'm aware it's a quirky design decision, and it's not
one I made on my own. The upside is that there is less code and more
convenience; the downside is that it may be trickier for humans to read
the code, and there is a slight performance penalty for using doubles as
an index. If it proves to be insupportable we can refactor it. Thanks
again.

*** Sent via Developersdex http://www.developersdex.com ***
Jul 16 '08 #5
On Jul 16, 1:29*pm, Bob Hoeppner <boba...@hotmai l.comwrote:
Yes, I see my understanding was flawed. It makes sense the one ternary
operator would have to return one datatype. This demonstrates that the
ternary operator is not an exact shorthand equivalent for an if/else
statement. Thanks.

Yes, I'm treating two collections as similarly as possible. There are
many bools and fewer doubles. Also, there is a lot of assigning of bools
to doubles and doubles to bools, due to the nature of the two systems
I'm interfacing. I'm aware it's a quirky design decision, and it's not
one I made on my own. The upside is that there is less code and more
convenience; the downside is that it may be trickier for humans to read
the code, and there is a slight performance penalty for using doubles as
an index. If it proves to be insupportable we can refactor it. Thanks
again.

*** Sent via Developersdexht tp://www.developersd ex.com***
I find a little weird that double to bool (and viceversa) asignation.
considering that bool as only two possible values.

could you explain a little more what are you doing?
Jul 16 '08 #6
this.m_unit.Add ((unittype == "b")? unitnum:(double )unitnum);
>
The bool dictionary uses an integer index, the double uses a double
index, which some may take issue with, but that's a different
discussion. The problem is that unitnum is always cast to a double, even
when unittype is "b". That seems like a bug to me.
I just looked in the C# Annotated Standard...

The semantics of the ternary operator requires the type of the expression to
be determined at compiled time. So (condensing several rules into one
sentence) it is whatever is compatible with both of the expressions after
the ? .
Jul 16 '08 #7
I've entered into that discussion on this thread

http://www.developersdex.com/csharp/...1111&r=6224121
Suffice it to say that the overloading of the indexers allows some more
concise code by people programming to the class, which is how those
coding to it prefer. We went over the various ways it could be
implemented. Some lines can get quite long. Here's a shorter one:

Grp.Unit[2770] = FUN(Grp.Unit[772] && !Grp.Unit[2771], ref
Grp.Unit[1800d], Grp.Unit[773d]); // Line 1290

which isn't much of an advantage over, say,

Grp.UnitB[2770] = FUN(Grp.UnitB[772] && !Grp.UnitB[2771], ref
Grp.UnitD[1800], Grp.UnitD[773]); // Line 1290

but when going between booleans and doubles, is, as described in my post
in the other thread.


*** Sent via Developersdex http://www.developersdex.com ***
Jul 16 '08 #8
Bob Hoeppner wrote:
Yes, I see my understanding was flawed. It makes sense the one ternary
operator would have to return one datatype. This demonstrates that the
ternary operator is not an exact shorthand equivalent for an if/else
statement.
I think you in general should avoid ?: with different data typesto keep
the code easy to read.

Arne
Jul 17 '08 #9

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

Similar topics

6
3836
by: praba kar | last post by:
Dear All, I am new to Python. I want to know how to work with ternary operator in Python. I cannot find any ternary operator in Python. So Kindly clear my doubt regarding this __________________________________ Yahoo! Messenger
6
2766
by: glongword | last post by:
As the assert macro should evaluate to a void expression, it should not have an 'if statement' in its definition. Does this necessitate the existence of a ternary conditional operator? Is there a way assert.h can be implemented without using it? Are these decisions related in anyway?
6
2990
by: Robert Zurer | last post by:
In his paper on Coding Standard found on http://www.idesign.net/idesign/DesktopDefault.aspx Juval Lowy discourages the use of the ternary conditional operator with no specific reason given. I can understand that complicated code would be much less readable using nested operators, but aside from that is there another reason? -- something going on under the hood perhaps which make it inadvisable to use?
2
1457
by: Darren | last post by:
Hi there, Recently I have changed languages from VB.NET to C#. While in VB.NET, I wrote the below code to determine if a specific product in a repeater control had an image. If so, it would display the appropriate image; if not, would display a placeholder.gif. I now need to convert the below code to C# and am having a brutal time at it. I do understand the simple syntax behind using the ternary
48
2759
by: Daniel Crespo | last post by:
Hi! I would like to know how can I do the PHP ternary operator/statement (... ? ... : ...) in Python... I want to something like: a = {'Huge': (quantity>90) ? True : False} Any suggestions?
15
12725
by: Arthur Dent | last post by:
Hi all, im just curious if anyone knows..... With .NET 2, VB didnt happen to get a true ternary operator, did it? Stuck away in a corner somewhere? By ternary, i mean something like C's a?b:c syntax. IIf works in most cases, but in some instances you want to use expressions which may fail if they are evaluated when they arent supposed to be, and it would be nice to have a concise way of writing this instead of using a whole If-Then-Else...
5
3567
by: PerlPhi | last post by:
hi,,, while ago i was wondering why do some programmers rarely uses the ternary operator. wherein it is less typing indeed. i believe in the classic virtue of Perl which is laziness. well let me show you something first before i go to my delimma. codes as follows using Mrs. If Else: #!perl/bin/perl use strict; print "Are you sure you want to quit ('yes' or any key for 'no'): "; chomp($_ = <STDIN>);
4
2390
by: raiderdav | last post by:
I understand how the ternary operator (question mark - ?) works in an if/else setting, but what does it mean when used as a type? For instance, I'm trying to add a get/set in some existing code, but the return type doesn't match: Rectangle? m_textArea = null; public Rectangle TextArea { set { m_textArea = value; } get { return m_textArea; }
0
9492
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10360
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
10163
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
8988
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
7510
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
6744
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
5397
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
5532
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3668
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.