Data Types & Arithmetic Expressions

Credits

Operators / and %

Examples of the / and % operators

Expression Types

The data ype of each variable must be declared, but how do you determine the data type of an expression?

It depends on its operands. If all operands are of type int, then the expression is of type int. Otherwise it is of type double.

e.g.

x+y

If x is an integer, and y is a double, then x+y is a double

If x is an integer, and y is a integer, then x+y is a integer

Mixed-Type Assignment

When an assignment statement is performed, the expression is first evaluated, then the result is assigned.

A common error is to assume that the type of the variable will force the expression to be evaluated as if it were of that type. This is not the case.

e.g.

int x=5, y=2;

double z=x/y;

z is now equal to 2.0 because the expression was evaluated using integer division not regular division.

When you assign a number of type double to an int variable, the fractional part of the number is dropped.

e.g.

int x=13*0.5;

int y=1*.99;

In this example x is evaluated as 6, and y is evaluated as 0.

Rules for Expression Evaluation

NOTE: Binary operators are used on two numbers at once, while unary are only used on one (such as -y to get negative y).

e.g.

a*b*c+d/e-f*g

is the exact same expression as

(a*b*c)+(d/e)-(f*g)

Casting

Placing the name of a different type in parentheses before a value will change, or cast, the value to the new type.

e.g.

(int)5.733

has a value of 5

Casting has a very high-precedence, being performed before multiplication and division.