Академический Документы
Профессиональный Документы
Культура Документы
Assignment Operators
C++ provides several assignment operators for abbreviating assignment expressions Any statement of the form:
variable = variable operator expression;
Where operator is one of the binary operators +, - , *, /, or % You can also do a short hand:
variable operator=expression;
operators
Assignment Operators += -= Sample Expression c += 7; c-=7; Explanation Add 7 to c and put the results in c. Subtract 7 from c and put the results in c Multiply 7 by c and put the results in c Divide c by 7 and put the results in c Find the reminder of C divided by 7 and put the results in c
*=
c*=7;
/= %=
c/=7; c%7;
Increment/Decrement operators
Example: i=10; cout <<++i << endl; // 11 will be printed out. i=12; cout <<i++<<endl; // 12 will be printed out.
Cast Operators
You can convert one data type to another. This is called casting. Syntax
(type) variable
Association is from left to right. C++ evaluate expressions of the same type To make sure the compiler does this correctly you need to force the conversion
Cast Operator
double sum; integer a=9; integer b=2; sum = (float)a/b; // The results will be 4.5 placed in sum.
Promotion hierachy
long double double float unsigned long int long int unsigned int int unsigned short int short int unsigned char char
Promotion Hierarchy
Note Each data type is at least as big as the one immediately below it in the hierarchy unsigned int are positive only short uses least number of bytes long uses maximum number of bytes double users >= number of bytes as float long double uses >= number of bytes as double
Logical Operators
Logical and && Logical or || As previously described, used to create more complex logical expressions.
if( gender ==1 && age >= 65) ++seniorfemales; if (semesterAverage>=90 || FinalExam >90) ++deanslist; if ( !( I>10 || J <50)) Count ++;
Operator confusion
Very common to swap = and == Does not usually cause syntax errors
Any expression that produces a value can be used to indicate true of false
If value is zero (0) is it treated as false If a value is not zero (0) it is treated as true
Assignments produce values Example if (paycode =4 ) cout << you got a bonus\n;
The previous statement will always be evaluated as true paycode value is changed Some compilers issue a warning but not always. Can avoid by putting the literal first.
if (4 == paycode) cout << you got a paycode\n;