Wednesday, January 9, 2013

Expressions and Operators

Arithmetic operators

Here are the most common arithmetic operators


*, / and % will be performed before + or - in any expression. Brackets can be used to force a different order of evaluation to this. Where division is performed between two integers, the result will be an integer, with remainder discarded. Modulo reduction is only meaningful between integers. If a program is ever required to divide a number by zero, this will cause an error, usually causing the program to crash.
Here are some arithmetic expressions used within assignment statements.

velocity = distance / time;

force = mass * acceleration;

count = count + 1;
C has some operators which allow abbreviation of certain types of arithmetic assignment statements.

These operations are usually very efficient. They can be combined with another expression.


Versions where the operator occurs before the variable name change the value of the variable before evaluating the expression, so


These can cause confusion if you try to do too many things on one command line. You are recommended to restrict your use of ++ and -- to ensure that your programs stay readable.
Another shorthand notation is listed below


These are simple to read and use.

Comparison

C has no special type to represent logical or boolean values. It improvises by using any of the integral types char, int, short, long, unsigned, with a value of 0 representing false and any other value representing true. It is rare for logical values to be stored in variables. They are usually generated as required by comparing two numeric values. This is where the comparison operators are used, they compare two numeric values and produce a logical result.



Note that == is used in comparisons and = is used in assignments. Comparison operators are used in expressions like the ones below.

x == y

i > 10

a + b != c
In the last example, all arithmetic is done before any comparison is made.These comparisons are most frequently used to control an if statement or a for or a while loop. These will be introduced in a later chapter.

0 comments:

Post a Comment

Powered by Blogger.