Type Casting in C and C++

Hello NG

As an old style programmer I've been casting values with the C-syntax like:

double dVal=3.14;
float fVal = (float) dVal;

but now I've been told that the C++ syntax should do a better job

float fVal = static_cast <float>(dVal);

for some reason. Is this true? Will the C++ compiler really generate 
different (better?) code or is it simply more writing I have to do?


5/3/2006 7:33:07 AM
vc.mfc 33608 articles. 0 followers. Follow

1 Replies

Similar Articles

[PageSpeed] 13

>As an old style programmer I've been casting values with the C-syntax like:
>double dVal=3.14;
>float fVal = (float) dVal;
>but now I've been told that the C++ syntax should do a better job
>float fVal = static_cast <float>(dVal);
>for some reason. Is this true? Will the C++ compiler really generate 
>different (better?) code or is it simply more writing I have to do?

The compiler is unlikely to do anything different in that case, but it
is safer to use the new style casts for a variety of reasons

1. static_cast is fairly mild in what you're able to do with it, the
compiler will moan if you're doing something naughty.
2. The new casts are quite specific in what they do.
3. You can search for them easier in source code.

davidl7375 (2060)
5/3/2006 2:10:32 PM

Similar Artilces:

Pie of Pie Chart type with smaller pie showing slices of main slic
Hi How can I do the following: Lets say I have the following labels and data For the main pie I have A,B,C labels with A =5, B =10, and C =20. So my main pie would show 3 slices with C being the largest slice. To do this I highlight the 3 labels and their data and choose Insert, Pie, Pie in a Pie to show a main pie on the left with 3 slices and a smaller solid pie to the right with series lines connectiing them. I want to show the solid smaller pie on the right in several slices to show how the C slice of 20 is broken down. lets say the main slice C of 20 is made up ...

Typing in macros
I have made a few macros and use them in word and excel 2000. When I see typed out macros on the message boards I am not quite sure how to use them. Do I go into the editor, type them in and then link them with a button on the toolbar? What module do I put them in and is there one for the personal worksheet. I have been struggling with the syntax of Visual Basics for years. Just need a step by step explanation. Thank You Sue In general, the macros you see in the groups are likely to be ordinary macros that will go into a general module in the VBE, eg:- Hit ALT+F11 and this will...

Open File Dialog to fileter multiple file types at once...?
Hello, Here is another quick one for you all. The solution is probably simple, but I cannot find the answer anywhere. I have the following code: CFileDialog OpenDlg(TRUE, NULL, NULL, OFN_ALLOWMULTISELECT | OFN_HIDEREADONLY, ""); // Later must set this to retrieve a value from the registry OpenDlg.m_ofn.lpstrInitialDir = "c:\\"; OpenDlg.m_ofn.lpstrFilter = "txt Files\0*.txt\0Doc Files\0*.doc\0"; OpenDlg.DoModal(); I am trying to get the box to filter out everything but the *.doc and the *.txt files ... I have seen some boxes that have something that...

Rectification of wrong posting type
Hi There is one PL account say "Mic Expenses" has got wrong posting type "Balance sheet", when we closed the year 2005 ,System has brought forward the balance of that account into next year 2006, which otherwise should have been gone into the Retain Earning of 2006, is there any option to rectify this error, other then passing rectifying JV in 2005(coz in that case if I take last year TB then ending balance of this account would be Zero) or restoring the backup and doing closing procedure again. Thanks in Advance Shabnam There is a Article ID for this in partner s...

Some chart types cannot be combined with other chart types?
Hi, I am getting the above error message everytime I try to insert a chart or any type into a completely blank presentation using either the Insert, Chart command or the Insert Chart button in the Title and Content slide layout. I am using 2007. Any help or suggestions would be appreciated. TIA, Shane Devenshire Try running Office Diagnostics, Shane. Open PPT or Excel, hit the Office button, then <app> Options | Resources. I think that may resolve this issue. -- Echo [MS PPT MVP] http://www.echosvoice.com What's new in PPT 2007? http://www.echosvoice.com/2007...

need help to declard type=IntType instead type="xsd:int" with xml schema
Hi, I am writing C# code to produce xml schema. //Create attribute XmlSchemaAttribute att2 = new XmlSchemaAttribute(); att2.Name = "CustomerID"; att2.SchemaTypeName = new XmlQualifiedName("int",schemaNS); att2.Use = XmlSchemaUse.Required; ct.Attributes.Add(att2); I need to produce schema with custom data type instead of the xsd:string or xsd:int The code above will produce the following schema <?xml version="1.0" encoding="utf-8"?> <xsd:schema attributeFormDefault="unqualified" version="1.0" xmlns:xsd=...

Media Player in C++ App
I've searched the threads but haven't seen this problem yet. Using VC++6 sp6 MFC. I have embedded the Media Player Active X into a dialog box. The resources show the proper media player default skin. Have filled out the properties and URL file (a MP3 file). When compiled, everything checks out. When I open the dialog box with DoModal(), the dialog box appears, the file plays but no media player is visible. Tried same with video file. sound is heard but again no player. Right mouse clicks bring up menu items and such and about shows the proper media player (9). First shot I just ...

Scatterplots with different colors based on Type of Data
Is it possible to plot a scatterplot with different colors for 2 sets of data? E.g Type of Agreement MRP Discount% Limited 10 5% UnLimited 20 10% I want to show different colors for Limited & Unlimited. Is it possible to plot scatterplots on both axis(Primary & Secondary) Please let me know. Thanks, Satish If I use this range to make a chart Limited 10 5% Unlimited ...

outlook type interface
I have an SDI application and want to change it so I have a split window, on the left I want a TreeControl above a 'PropertyGrid' control. Then my exisiting SDI Client in the space on the right Can anyone point in the right direction to achieve this Any help will be much appreciated Thanks Phil You need to use two CSplitterWnds (as members of your CMainFrame). Override CMainFrame::OnCreateClient and create a vertical splitter as the main child (i.e. 1 row, 2 cols). Then you want to create a horz splitter as a child of the left-hand pane of the main splitter (which has 2 rows, 1 c...

VSTO Excel 2003 to VB 6.0 Type mismatch
Hi, I have an Addin 2003 Application. In this Application I'm calling an VB 6.0 Dll and I send Excel Application Object as Parameter. In VB Project I'm using Workbook_Open event with WithEvents. I have a messagebox there. Unfortunately when i call VB dll , I get this Error Message -- > Type mismatch. Is there any Idea? Code in VS2008 : private Project1.Class1 vbapp; private void ThisAddIn_Startup(object sender, System.EventArgs e) { #region VSTO generated code this.Application = (Excel.Application)Microsoft....

predictive typing of addressee
I am frequently sending sensitive email to a person who has a very common name. More than once I have almost sent the email to the wrong party because of the Outlook feature that predicts the addressee name. Does anyone know how to eliminate names from the dropdown list that appears as you type tha addressee name? Or is there a way to stop addressee names from appearing automatically as you type in the "To" field. Any help will be appreciated. joanne Use arrow keys to highlight error address, then hit Delete Btn Do you use Contacts?, hitting the 'To' Btn will bri...

How to collapse C# XML doc comments like in VB.NET
Anybody know how I can set environment in C# so that when you will press "-" sign in front XML doc comment (///) it will collapse like in VB.NET, With that i mean you will see only summary text and not only <summary> tag. Let me show example and results in both languages. In VB.NET: ''' <summary> ''' Add two whole numbers ''' </summary> ''' <param name="intNr1">First number</param> ''' <param name="intNr2">Second number</param> ''...

How to convert CString type to LPCSTR type
Hi, I have a CString type variable, and I need to convert it's to LPCSTR type ,what I can do! example: CString m_strExecFile(_T("C:\\\\aa.exe")); next I want to call WinExec Command to execute this file LPCSTR lpcstr ; lpcstr = m_strExecFile.GetBuffer(); WinExec(lpcstr,SW_SHOW); BUT the compilier tells me it can not convert w_char * to LPCSTR type! Why? ps. I use vs2005 program in UNICODE mode. Any helpful ideas would be highly appreciated! -joseph Why use a CString in this case at all, if all you are doing is using it in WinExec. Something ...

"Can't change data type" error
I'm trying to reduce the field size of text fields in my database. They defaulted to 255 characters when I created my database but in many cases I only need a size of around 20. When I enter the reduced size for one field in the table design view and try to save the change to that field I get the following errors: "Microsoft Access can't change the data type. There isn't enough diskspace or memory." When I click OK to the above I then get the following message: "Errors were encountered durnig the save operation. Data types were not changed. Properties w...

Aggregate data types mismatch
Using reporting services 2008. Getting a really weird error when calculating a variance between a budget and actual amount in the report. Both the underlying fields are of data type 'money', but when performing the calc in the report writer, i am getting the following error: [rsAggregateOfMixedDataTypes] The Value expression for the textrun 'Variance_MTD_ActualvsBudget1.Paragraphs[0].TextRuns[0]' uses an aggregate function on data of varying data types. Aggregate functions other than First, Last, Previous, Count, and CountDistinct can only aggregate data of a si...

Change types
I hav got a letter with types that i cannot understand. When i mark some of the words, tells me that this type is sansserif. I think that this is a joke but i cannot find out how to change to arial or times new roman ...

Determining address of value type variables
How to get the address of(memory location) value type variables? GetHashCode() returns only value and not its address Thank you Regards Raj "Raj" wrote: > How to get the address of(memory location) value type variables? > > GetHashCode() returns only value and not its address > > Thank you > > Regards > Raj An address in memory and a hashcode have nothing to do with each other. You should rarely, if ever, need to get an address of any .net object. To get an address in memory, you need to use unsafe code and the "&a...

Advice for type of chart
I'm comparing the sugar content of different beverages. However the values vary for example cocktails may have between 90-130 grams per liter and vegetable juices perhaps 40-100 grams. Which type of graph should I use to represent the various drinks and show the single variations rather then their averages? Thanks, Rob Hi you could try using a "high low close" format, with the "close" value set equal to the high or low to make it effectively a "high low chart. Or, a stacked bar with the first series set to colour none, line colou none, has a similar effec...

CRM API: Converting an Object Type value -> ObjectType
I've setup post callouts in CRM which notify me when a CRM object has been modified. CRM sends me the ObjectType value so I know what type of object has been modified. For example 1 for an Account, 132 for an Activity... I can't figure out however how to convert the number back into an ObjectType. In theory it should be very simple, but from what I can tell the ObjectType class is NOT an Enum, oddly enough. I've tried the following: int objectTypeValue = 2; // which is a Contact // returns otActivity test = (ObjectType) Enum.ToObject(typeof(ObjectType), objectTypeValue); // r...

Possible reasons for a C++ exception being thrown for line three?
std::string MatchedSTRING; String2MATCH[1000]; if (MatchedSTRING != String2MATCH) { My first guess was an index out of bounds error. should have said: char String2MATCH[1000]; "Peter Olcott" <NoSpam@SeeScreen.com> wrote in message news:g76Yh.18159$2Q1.749@newsfe16.lga... > std::string MatchedSTRING; > String2MATCH[1000]; > if (MatchedSTRING != String2MATCH) { > > My first guess was an index out of bounds error. > It would be alot easier to diagnose if we had some idea how long the strings were, or what kind of exception was thrown, and by whom, an...

Type/Type ID
How easy or difficult is it to create a document type/id other than the GP defaults? We give some of our customers items on consignment and we would like to be able to track these items and create a subsequent invoice. You can't create a document type. You have to use the ones in the system because they are hard-coded. You can create all the document type ids you want. Do you use a consignment site in GP? If you put items into that site, then you will be able to track what is on consignment and you can enter orders against it. When you post the invoice, the quantity on hand for t...

Investment Type
A mutual fund that holds bonds has been imported from Quicken as a bond fund. As such, the symbol CNN.UN is not recognized for automatic updating. Is there a way to change Investment Type: BOND to Investment Type: Mutual Fund? Have a look at http://www.bollar.org/msmoney/#Q81 which shows how to change from one type to another/ -- Glyn Simpson, Microsoft MVP - Money Check http://support.microsoft.com/default.aspx?scid=fh;EN-GB;mny for UK tips and fixes for MS Money. To send Microsoft your wishes or suggestions, use http://register.microsoft.com/mswish/suggestion.asp or email mnyukwsh@...

Redefine field data type
Hi, I am trying to write a function in a module in MS Access 2000 that will change the data type of a field called 'Start' in table 'bo_cpm_CS01ALL'. Here is the code that I have done so far but when I run it nothing happens...no errors or changes to the table. The code finds the table and field, creates a new field called 'temp' then copys 'Start' to 'temp' then deletes 'Start' and renames 'temp'. The field 'Start' has data type dbDouble. Any help would be great!! Public Function ChangeFieldType() 'Purpose: Changes a f...

Data Type Problem
Hi Experts In VC++, the maximum range for data type is 10 bytes which is the range for long double __int64 has 8 bytes range. Is there any data type which has range more than 10 bytes? Is there any data type which has range 16 bytes If not supported, then can i create my own data type which range should be more than 10 bytes? if yes then please reply thanks If you need to play with huge sections of numbers, you can always use a unsigned char array, and use bit shifting backwards and forwards for calculation (complex). Otherwise, for numbers there are other string ba...

types of email
Just set up Outlook 2003 and a personal address book since I'm more use to that format than contacts. When putting in a new entry one of the boxes that needs to be filled out is "E-mail type". What should I be using and how many types are there? I'd appreciate some help. Couldn't find anything in the help menus. -- Ron You really would be better off using Contacts, its not a steep learning curve, and will likely provide better integration. Checking the wab, on another sys, I can find no refference to 'email type' and there appears v.little difference bet...