Search code examples
ethereumsoliditysmartcontracts

Solidity, assigning multiple values with "=" in the same line


Where can I get a detailed explaination of this weird assignment in solidity?

The one in the constructor. Multiple = = = .

Couldn't find anything in the official docs.

contract Token {

  mapping(address => uint) balances;
  uint public totalSupply;
  uint public anotherUint = 10;

  constructor(uint _initialSupply, uint _anotherUint) {
    balances[msg.sender] = totalSupply = anotherUint = _initialSupply = _anotherUint;
  }

  function transfer(address _to, uint _value) public returns (bool) {
    require(balances[msg.sender] - _value >= 0);
    balances[msg.sender] -= _value;
    balances[_to] += _value;
    return true;
  }

  function balanceOf(address _owner) public view returns (uint balance) {
    return balances[_owner];
  }
}

Solution

  • It's an example of chained assignment, that is available in many other programming languages.

    Example in JS:

    // copy paste this to your browser devtools console to explore how it works
    
    let _initialSupply = 5;
    let _anotherUint = 10;
    let anotherUint;
    let totalSupply;
    
    const balance = totalSupply = anotherUint = _initialSupply = _anotherUint;
    

    It assignes:

    1. value of _anotherUint to _initialSupply (overriding the value passed in constructor)
    2. (the new) value of _initialSupply to anotherUint
    3. value of anotherUint to totalSupply
    4. and finally the value of totalSupply to the balances[msg.sender] (or in my JS code to balance)

    Solidity docs don't seem to cover this topic, but it's not explicit to Solidity only.