0
if(_newDelegate != delegateContract){    
    // Do something 
}

require(_newDelegate != delegateContract){
    // Do something 
}

Could anyone explain difference between if and require in solidity? When to use if and require? I taught both are same and can be used alternatively.

1
if (_newDelegate != delegateContract) {
  // do something
}

is just a conditional execution of the // do something block. So if that condition is not met, the // do something block is skipped. But the execution moves to the next line after that block.

You use require when you wish to revert the entire state changes so far in the function if some condition is not met. For example,

uint256 input;
address sender;

function some_state_changing_fn (uint256 _input) public returns (bool success)
{
  sender = msg.sender;
  require(_input >= 100);
  input = _input;
  success = true;
}

In case _input is less than 100, you don't want even sender to be updated to msg.sender. So when the require fails, the entire transaction is reverted. This may not seem so relevant in the function body above. But there are instances where you call another contract, transfer some tokens, etc. For such situations, the require is an extremely safe way to handle failures or conditions not being met in solidity.

Please refer this: https://solidity.readthedocs.io/en/v0.4.25/control-structures.html?highlight=require#error-handling-assert-require-revert-and-exceptions

| improve this answer | |
0
  • The if is the normal if statement found in any language; nothing strange here.

  • The require is something different: it means:

“only in the case that the condition is met, the elaboration can go on; otherwise stop it, nullify all changes done to whatever variable in the smart contract during this run, abort the transaction which originate the call, etc.

(-> see revert instruction to have the list of all the effects: require fire a revert if the condition is not met!)

In short require is the same thing that:

if(<condition to be met> is false) ABORT ALL FROM THE START AND CANCEL ANY EFFECT THAT THE PREVIOUS ELABORATION MADE

Hoping to be of some help!

| improve this answer | |

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.