int vs. typecast

Code/IDE output below. The tutorial was extolling the virtues of using static_cast over integer assignment in converting integer to ASCII. I have both methods listed below. I want to know why the second is "better" then the first. It seems that they produce the same result.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include<iostream>
using namespace std;

int main()
{
char c;
cout<<"enter your symbol"<<endl;
cout<<"Symbol: ";
cin>>c;
cout<<"Symbol :"<<c<<"     ASCII :"<<int(c)<<endl;
cout<<"using type_cast"<<endl;
cout<<"Symbol :"<<c<<"     ASCII :"<<static_cast<int>(c)<<endl;

return 0;
}


1
2
3
4
5
6
7
output:

enter your symbol
Symbol: g
Symbol :g     ASCII :103
using type_cast
Symbol :g     ASCII :103
Last edited on
google.
http://stackoverflow.com/questions/1609163/what-is-the-difference-between-static-cast-and-c-style-casting

also, another advantage I've found is that c++ casts are easier to search for in a huge c++ project, and c casts are fairly impossible to find.
Last edited on
> I want to know why the second is "better" then the first

That static_cast<int>(c) is 'better' than int(c) or +c is a matter of opinion.
For the record, I do not agree with it.

This is what I tend to do:

To cast a simple value to a prvalue of another type, I use a Pascal-style cast (functional notation):
for instance, double(end_time-start_time)

To cast away the const qualifier, or to cast across references or pointers at compile-time, I use the C++ casts. In practice, I hardy ever need this kind of cast in my code; when I do need it, it almost always is a reinterpret_cast<>

For (references and pointers) to object-oriented types, I always use the run-time cast dynamic_cast<>. I hardy ever need this kind of cast either, except in debugging scaffolds and test frames.
Thanks that is very helpful. Last Q: what real life scenario would one find himself(or her) in which type-casting is necessary in addition to what you have enumerated : )
Textbook examples:
const_cast: implementing non-const accessor in terms of const one. Explained in by Meyers in Effective C++ book.

reinterpret_cast: casting pointers to [unsigned] char and back when dealing with byte-twiddling (saving objects to binary file, etc)
Topic archived. No new replies allowed.