Source Code. Projects. Nerd Stuff. Art Stuff.

Lesson 1: Type Casting

Type Casting

Type Casting

  • Type Cast – an expression to make a value look like it has a different datatype. Type casting never changes the datatype of a variable — that’s impossible. Instead, a type cast is like a function that returns the same value in a different datatype.
  • Old Notation – The old notation for type casts uses the type name only. E.g. to cast the variable x to type double, you could write:
    1
    double(x)

    or

    1
    (double)x

  • New Notation – There is a new notation for type casts which uses the keyword “static_cast” E.g. to cast the variable x to type double, you write:
    1
    static_cast<double>(x)

  • Any of the above notations should work on an up-to-date C++ compiler, but try to get used to the new notation and use that one.
  • Example use of casting: avoiding truncation in integer division. Remember that the result of a division operation will be truncated to an integer if both the operands were integers. So to get an accurate floating point result, cast one of the operands to a floating-point type. So for example when finding the average word length in a document:
      int num_chars, num_words;
      float avg_length;
    
      cout << "How many characters are in the document? ";
      cin >> num_chars;
      cout << "and how many words are there? ";
      cin >> num_words;
    
      avg_length = static_cast<float>(num_chars) / num_words;
    
      cout << "The average word length is " << avg_length << " characters.\n";
    
      /* Sample Output:
    
      How many characters are in the document? 100
      and how many words are there? 28
      The average word length is 3.57143 characters.
    
      */
      // without the type cast, the average word length calculated would have been 3