現在,是時候研究c++操作符了。在c++中,操作符作用於變量和值。大多數操作本質上是數學或邏輯的。c++有豐富的內置操作符,並提供了以下類型的操作符−
- 算術運算符用於對兩個或多個操作數執行算術運算。一些常見的操作數是+(加法)、-(減法)、*(乘法)、/(除法)、%(餘數)、++(增量)、——(減法)。對如
我+ +;Sum = a + b;
B.Relational Operators they are used to determine the relation between variables or values. Here, we compare two values and return the result as either true (1) or false (0). Some common relational operators are as == (check equality), != (checks inequality), > (greater than), < (lesser than), >= (greater than or equal to) and <= (less than or equal to).
如。
if (x>THRESHOLD){…}
- Logical Operators used to determine the logic between variables or values. Logical operators are && (Logical AND),|| (Logical OR Operator) and ! (Logical NOT operator).
如。
If (x<5 && y>10) {}
D.Bitwise Operators Bitwise operator does not work on numbers but on bits. It is done bit-by-bit operation. The three Bitwise operators are & (bit wise AND), | (Bitwise OR), ^(Bitwise XOR), ~ (binary 1’s complement), << (binary left shift operator) and >> (binary left shift operator).
E.Assignment Operators This class of operators are used for assignment. For e.g = (simple assignment), += (add AND assignment), -= (subtract AND assignment), *= (multiply AND assignment) etc.
F.Misc Operators They are a heterogeneous operator set. It includes sizeof (used to find size of a variable), ternary operator condition ? exp1: exp2 (conditional evaluation), , operator, .(dot) and -> (arrow), cast (change type of a variable temporarily) , & (pointer address) and *(pointer access)
運算符的優先級和結合性也很重要。優先級規定了不同操作符執行的優先級,而結合性給出了操作符的求值方向(從左到右或從右到左)。它們都影響表達式的求值方式。例如,乘法運算符的優先級高於加法運算符,因此*將在+之前求值。
例如:
X = 7 * 5 + 3 - 2 * 10;//x等於18