Assigning Values to Variables


You assign a value to a variable by using the assignment operator = (an equal sign). The value on the right side of the operator is stored in the variable on the left side. When assigning a value to a variable, the value must belong to the same type as the variable, be a type for which C++ will perform an assignment conversion (such as between float and integral types), or be explicitly cast to the correct type.

start sidebar
Assignment Conversions

Assignment conversions occur when variables on opposite sides of an equal sign are of different types and the compiler can convert between the two types without any possible loss of data. For instance, assigning an integer to a double will result in an assignment conversion because all the compiler has to do is to add .0 to the integer to make the conversion.

You might occasionally need to tell the compiler to perform a conversion that it otherwise wouldn’t do. For example, dividing two integers will result in an integer result: if you want a floating point result, you can tell the compiler to convert one of the values to a double, like this:

double result = double(640) / 480;

You give the name of the type to convert to, followed by the value in parentheses. This process is called casting, and it can be rather dangerous because you’re telling the compiler to apply a conversion, and you’d better be sure you’re correct.

int x; float y; double z; x = 1; z = x; y = 3.56; x = y; // Assignment conversion from float to int // results in loss of data. // The integer 3 is stored in the variable x.

The compiler will generate the warning “C4244: ‘=‘ conversion from ‘float’ to ‘int’ possible loss of data.” The reason for this is that the assignment to an integer will lose the fractional part, so 3.56 will be truncated to 3.

end sidebar




Microsoft Visual C++  .NET(c) Step by Step
Microsoft Visual C++ .NET(c) Step by Step
ISBN: 735615675
EAN: N/A
Year: 2003
Pages: 208

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net