Thread: Convert a variable's datatype

  1. #1
    Registered User
    Join Date
    Nov 2010
    Posts
    5

    Question Convert a variable's datatype

    Hello all,

    Is it possible to convert a single variable's datatype several times in code? If so, is it frowned upon? It saves space though so you don't have to use new variables.

    Here is an example:
    Code:
    float i;                //i is float here
    i=456.79835;
    i=(int)i;              //i changes to integer here
    Thanks!

  2. #2
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    You say "i changes to integer here", but it doesn't. i is still a float variable, and will always and forever be a float variable. You can put an integer value in it, but that doesn't change the type of the variable just as
    Code:
    float i = 1; //i is still a float variable, even though 1 is an int

  3. #3
    Registered User
    Join Date
    Nov 2010
    Posts
    5
    Ah, ok so I do need to make another variable specifically for the datatype...

    Thanks.

  4. #4
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Yes, if you need the variable to have a different type, just create a new variable of that type.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Best way to avoid using global variables
    By Canadian0469 in forum C++ Programming
    Replies: 7
    Last Post: 12-18-2008, 12:02 PM
  2. Father and Son Variables
    By khdani in forum Linux Programming
    Replies: 3
    Last Post: 11-28-2008, 06:42 PM
  3. hwnd and variables in them
    By underthesun in forum Windows Programming
    Replies: 6
    Last Post: 01-16-2005, 06:39 PM
  4. Replies: 5
    Last Post: 09-05-2002, 10:16 AM
  5. functions to return 2 variables?
    By tim in forum C Programming
    Replies: 5
    Last Post: 02-18-2002, 02:39 PM