Thread: Data Types

  1. #1
    Registered User
    Join Date
    Jan 2010
    Posts
    12

    Data Types

    Is multiplying a floating point by an integer possible without converting the int to a floating point or vice versa?

    For instance, if I use my results are unexpected and I have a feeling it's due to the difference in data types:

    product = floatvar * intvar;

    Thanks,

  2. #2
    Officially An Architect brewbuck's Avatar
    Join Date
    Mar 2007
    Location
    Portland, OR
    Posts
    7,396
    Quote Originally Posted by Sn0wcra5h View Post
    Is multiplying a floating point by an integer possible without converting the int to a floating point or vice versa?
    Depends what you mean by that. CPUs do not (normally) have the ability to directly multiply integers with floats. If you mean, does the integer need to be converted to a float before the multiplication, then the answer is yes. If you mean, do you need to do this manually in the code, the answer is no.

    The C standard defines a set of type promotions which occur when computing arithmetic expressions with mixed types. If an expression involves an integer and a float, then the integer is implicitly converted to float before evaluating the expression. This is done on an operator-by-operator basis.

    For instance:

    Code:
    int a;
    float b;
    double c;
    
    double x = a - b * c;
    In this expression, b is converted from float to double, the resulting value is multiplied by c to produce another double. a is then converted to double, and the double value previously computed is subtracted from it. The overall type of the expression is double.

    You do not need to do anything special to cause this to happen.

    Your particular example of a float multiplied with an int is perfectly ok. If something is going wrong, the problem lies elsewhere.
    Code:
    //try
    //{
    	if (a) do { f( b); } while(1);
    	else   do { f(!b); } while(1);
    //}

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Extending basic data types.
    By nempo in forum C++ Programming
    Replies: 23
    Last Post: 09-25-2007, 03:28 PM
  2. Replies: 4
    Last Post: 06-14-2005, 05:45 AM
  3. Binary Search Trees Part III
    By Prelude in forum A Brief History of Cprogramming.com
    Replies: 16
    Last Post: 10-02-2004, 03:00 PM
  4. gcc problem
    By bjdea1 in forum Linux Programming
    Replies: 13
    Last Post: 04-29-2002, 06:51 PM
  5. Using enumerated data types
    By SXO in forum C++ Programming
    Replies: 7
    Last Post: 09-04-2001, 06:26 PM