Welcome, Guest. Please login or register. Did you miss your activation email?

Author Topic: C++ Type conversion  (Read 2206 times)

0 Members and 1 Guest are viewing this topic.

Lillebror

  • Newbie
  • *
  • Posts: 5
    • View Profile
C++ Type conversion
« on: January 03, 2011, 10:23:28 pm »
When, for instance, converting a float to an int there are a few ways to go about doing so. I was wondering what way is preferred by C++ programmers. int( floatVariable ), (int)floatVariable or some kind of casting?

Mr. X

  • Jr. Member
  • **
  • Posts: 80
    • View Profile
C++ Type conversion
« Reply #1 on: January 03, 2011, 11:14:37 pm »
int(var) is an initialization and creates a new integer object. Its no cast. If you can cast, its probably faster. (Ok, for an integer it makes most likely no difference)
(int)var is a cast (C style). The same as static_cast<int>(var) (C++ style) which is in my opinion the nicer syntax.

Laurent

  • Administrator
  • Hero Member
  • *****
  • Posts: 32504
    • View Profile
    • SFML's website
    • Email
C++ Type conversion
« Reply #2 on: January 03, 2011, 11:25:58 pm »
static_cast is the way to go.

C++ casts must always be preferred. C casts must be avoided, they are not made for C++ and can produce errors that are hard to track. Using the constructor is ok but it's weird for primitive types, it's more used with classes.
Laurent Gomila - SFML developer

Nexus

  • SFML Team
  • Hero Member
  • *****
  • Posts: 6286
  • Thor Developer
    • View Profile
    • Bromeon
C++ Type conversion
« Reply #3 on: January 04, 2011, 11:58:56 am »
Quote from: "Mr. X"
int(var) is an initialization and creates a new integer object. Its no cast.
Yes, it is called "function-style cast". It is to avoid like C-style casts because it has the same dangerous semantics (for example, it can accidentally cast away const).

The functionality of C-style and function-style casts is split into static_cast, const_cast and reinterpret_cast. Besides, C++ introduces dynamic_cast. You should use the specific operator for each conversion (mostly this will be static_cast). In general, a good style is to cast as few as possible, since many casts indicate a possible design flaw (wrong types chosen).

Quote from: "Mr. X"
If you can cast, its probably faster.
Faster than what?
Zloxx II: action platformer
Thor Library: particle systems, animations, dot products, ...
SFML Game Development: