Learning Objectives – after this chapter you will be able to:
  • Use arithmetic, assignment, relational, logical, bitwise and ternary operators.
  • Explain checked arithmetic (overflow protection) and unchecked blocks.
  • Predict the result of integer division and modulus, including negative numbers.
Operators

Solidity supports the following groups of operators:

  • Arithmetic Operators
  • Assignment (and compound assignment) Operators
  • Relational (comparison) Operators
  • Logical Operators
  • Bitwise and Shift Operators
  • Ternary (conditional) Operator
Arithmetic Operators

Arithmetic operators perform mathematical operations on integers. Solidity has no floating-point numbers, so all results are whole numbers.

OperationSymbolExample (uint)
Addition+7 + 2 = 9
Subtraction-7 - 2 = 5
Multiplication*7 * 2 = 14
Division/7 / 2 = 3 (result is truncated towards zero)
Modulus%7 % 2 = 1 (remainder of the division)
Exponent**2 ** 3 = 8
Increment++x++ adds 1
Decrement--x-- subtracts 1
Checked arithmetic (Solidity 0.8 and later)
  • If a result goes outside the type’s range – e.g. uint8(255) + 1 or 0 - 1 for a uint – the transaction reverts with a Panic error instead of silently wrapping around.
  • Division or modulus by zero also reverts.
  • Inside an unchecked { ... } block the checks are switched off and values wrap around (255 + 1 becomes 0). Use it only when you are sure overflow cannot happen, to save gas.
  • With signed integers, -7 / 2 = -3 and -7 % 2 = -1 (the remainder takes the sign of the left operand).
Assignment Operators

Assignment operators store a value in a variable; compound forms shorten common updates.

OperationSymbolEquivalent to
Assignment=a = b
Add assignment+=a = a + b
Subtract assignment-=a = a - b
Multiply assignment*=a = a * b
Divide assignment/=a = a / b
Modulus assignment%=a = a % b
Bitwise compound&= |= ^= <<= >>=a = a & b, etc.

The delete operator resets a variable to its default value (e.g. delete count; sets it to 0).

Relational Operators

Relational operators compare two values and return a bool.

OperatorReturns true if …
== (equal)both values are equal. Note: two equal signs! A single = is assignment.
!= (not equal)the values are different.
> (greater than)the left value is greater than the right value.
>= (greater than or equal)the left value is greater than or equal to the right value.
< (less than)the left value is less than the right value.
<= (less than or equal)the left value is less than or equal to the right value.

Strings cannot be compared with ==; compare their hashes instead (Chapter 9).

Logical Operators
OperatorMeaning
&& (logical AND)true only if both conditions are true.
|| (logical OR)true if at least one condition is true.
! (logical NOT)reverses a boolean: true becomes false and false becomes true.

Short-circuit: in a && b, if a is false, b is not evaluated; in a || b, if a is true, b is not evaluated. Putting the cheaper check first can save gas.

Ternary Operator

A short form of a simple if/else that returns one of two values:

condition ? valueIfTrue : valueIfFalse
uint larger = (a > b) ? a : b;
Bitwise and Shift Operators

Bitwise operators work on the individual bits (0 and 1) of integers. Example with a = 12 (binary 1100) and b = 10 (binary 1010):

OperatorMeaningResult
& (AND)1 where both bits are 11000 = 8
| (OR)1 where either bit is 11110 = 14
^ (XOR)1 where the bits differ0110 = 6
~ (NOT)inverts every bitfor uint8: ~12 = 243
<< (left shift)moves bits left (multiplies by 2n)12 << 1 = 24
>> (right shift)moves bits right (divides by 2n)12 >> 2 = 3
Example : Operators in a Contract
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

contract OperatorsDemo {
    function arithmetic(uint a, uint b) public pure
        returns (uint sum, uint diff, uint product, uint quotient, uint remainder, uint power)
    {
        sum = a + b;
        diff = a - b;            // reverts if b > a (checked arithmetic)
        product = a * b;
        quotient = a / b;        // reverts if b == 0
        remainder = a % b;
        power = a ** 2;
    }

    function compare(uint a, uint b) public pure returns (bool equal, bool bothPositive, uint larger) {
        equal = (a == b);
        bothPositive = (a > 0 && b > 0);
        larger = (a > b) ? a : b;        // ternary operator
    }

    function bitwise(uint8 a, uint8 b) public pure returns (uint8, uint8, uint8, uint8) {
        return (a & b, a | b, a ^ b, a << 1);
    }

    function wrapAround() public pure returns (uint8) {
        uint8 x = 255;
        unchecked { x = x + 1; }        // no overflow check: wraps to 0
        return x;
    }
}
Key Takeaways
  • Integer division truncates; there are no floating-point numbers.
  • Since 0.8, overflow, underflow and division by zero revert automatically; unchecked disables overflow checks.
  • Use == for comparison, = for assignment, and order &&/|| conditions to short-circuit cheaply.
Download | Print      E-Notes

The PDF E-Notes are the earlier printable version of this chapter. The notes on this page are the latest, revised version.

Question / Answer (15 questions)

Answer : Arithmetic, assignment (including compound assignment), relational (comparison), logical, bitwise and shift, and the ternary (conditional) operator.

Answer : 3. Solidity has no floating-point numbers, so integer division truncates the result towards zero.

Answer : It returns the remainder of integer division, e.g. 7 % 2 = 1.

Answer : The operation reverts the transaction with a Panic error, instead of silently wrapping around as it did in versions before 0.8.

Answer : unchecked { ... } disables overflow/underflow checks inside the block, so results wrap around and gas is saved. It should be used only when overflow is impossible, for example a loop counter with a known small bound.

Answer : The transaction reverts with a Panic error; division and modulus by zero are always checked.

Answer : = is the assignment operator that stores a value in a variable; == is the relational operator that compares two values and returns a bool.

Answer : In a && b, b is not evaluated when a is false; in a || b, b is not evaluated when a is true. Ordering conditions well can save gas and avoid unnecessary calls.

Answer : condition ? valueIfTrue : valueIfFalse, e.g. uint larger = (a > b) ? a : b;.

Answer : 12 = 1100 and 10 = 1010 in binary. AND = 1000 = 8, OR = 1110 = 14, XOR = 0110 = 6.

Answer : x << n moves bits left n places, multiplying by 2^n (12 << 1 = 24); x >> n moves bits right, dividing by 2^n (12 >> 2 = 3).

Answer : -7 / 2 = -3 (truncated towards zero) and -7 % 2 = -1 (the remainder takes the sign of the left operand).

Answer : It resets a variable to its default value, e.g. delete on a uint sets it to 0, on a bool to false and on an array element to the element’s default.

Answer : No. Strings are dynamic reference types and == is not defined for them. Compare their hashes, e.g. keccak256(bytes(a)) == keccak256(bytes(b)).

Answer : total += price;
MCQ Test : Check Your Understanding (5 questions)

Select an option and press Check Answer, or answer all questions and press Submit Test to see your score. Each answer comes with an explanation.

Q1. For uint values, 9 / 4 evaluates to:

Show Answer

Correct Answer : B. 2
Integer division truncates to 2.

Q2. In Solidity 0.8, uint8 x = 255; x = x + 1; (outside unchecked) will:

Show Answer

Correct Answer : C. Revert the transaction
Checked arithmetic reverts on overflow.

Q3. Which operator returns true only if both conditions are true?

Show Answer

Correct Answer : A. &&
&& is logical AND.

Q4. What is 12 >> 2?

Show Answer

Correct Answer : D. 3
Shifting right by 2 divides by 4.

Q5. Which statement about unchecked { } is correct?

Show Answer

Correct Answer : A. It disables overflow checks so values wrap around
unchecked only removes overflow/underflow checks; division by zero still reverts.

Bibliography/References

The notes, questions and MCQs on this page are original explanations written for this course. The works listed below were consulted and are cited for attribution and further reading. Product names, logos and trademarks belong to their respective owners. Short quotations, where used, are marked and attributed.

  1. Solidity Team. (n.d.). Types (value types, reference types, mappings, operators, conversions). Solidity Documentation. https://docs.soliditylang.org/en/latest/types.html
  2. Solidity Team. (n.d.). Expressions and Control Structures (if/else, loops, checked arithmetic, error handling, try/catch). Solidity Documentation. https://docs.soliditylang.org/en/latest/control-structures.html
  3. Solidity Team. (n.d.). Cheatsheet. Solidity Documentation. https://docs.soliditylang.org/en/latest/cheatsheet.html
  4. CoinsBench. (n.d.). Solidity #4: Operators & Conditions. https://coinsbench.com/solidity-4-operators-conditions-736a2c3faeff
  5. Modi, R. (2018). Solidity Programming Essentials: A beginner’s guide to build smart contracts for Ethereum and blockchain. Packt Publishing. ISBN 978-1-78883-138-3.