3

Consider this voting contract

contract Voting {
  mapping (bytes32 => uint8) public votesReceived;
  mapping (bytes32 => bool) public candidateList;
  function Voting(bytes32[] candidateNames) {
    for(uint i = 0; i < candidateNames.length; i++) {
      candidateList[candidateNames[i]] = true;
    }
  }
  function totalVotesFor(bytes32 candidate) returns (uint8) {
    require(validCandidate(candidate) == true);
    return votesReceived[candidate];
  }
  function voteForCandidate(bytes32 candidate) {
    require(validCandidate(candidate) == true);
    votesReceived[candidate] += 1;
  }
  function validCandidate(bytes32 candidate) returns (bool) {
    return candidateList[candidate];
  }
}

if I call validCandidate with a valid name (ie. a name included in the array passed to the constructor), it works. But for invalid names, I got a invalid opcode exception. I thought that maps had 0/false by default, is it not the case?

3

In solidity, the default value is 'zero', for uint is 0, bool is false. If you find a element that is included this mapping by key, so it returns default value.

In your contract, there is two unreasonable use, a function that doesn't modify status, you should declare a constant function.

contract Voting {

  mapping (bytes32 => uint8) public votesReceived;
  mapping (bytes32 => bool) public candidateList;

  function Voting(bytes32[] candidateNames) {
    for(uint i = 0; i < candidateNames.length; i++) {
      candidateList[candidateNames[i]] = true;
    }
  }

  function totalVotesFor(bytes32 candidate) constant returns (uint8) {
    require(validCandidate(candidate));
    return votesReceived[candidate];
  }

  function voteForCandidate(bytes32 candidate) {
    require(validCandidate(candidate) == true);
    votesReceived[candidate] += 1;
  }

  function validCandidate(bytes32 candidate) constant returns (bool) {
    return candidateList[candidate];
  }

}

It's a simple test as follows:

enter image description here Hope it helps~

0

Default Value of bool type in solidity is false. A simple smart contract to verify this.Run this in remix and click test.

pragma solidity ^0.4.24;

contract DeafaultValueOfBool{

    bool public test;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.