13

This question already has an answer here:

Browsing through the Ethereum docs I came across this modifier:

modifier onlyOwner {
    if (msg.sender != owner) throw;
    _;
}

I am not familiar with usage of _. What does it mean in this context?

marked as duplicate by Richard Horrocks, Tjaden Hess, Badr Bellaj, Rob Hitchens - B9lab, Matthew Schmidt Jul 1 '17 at 23:07

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

17

"_" is a special character that is used in functional modifiers. It returns the flow of execution to the original function that is annotated.

Taking your example...

modifier onlyOwner {
    if (msg.sender != owner) throw;
    _; <- here comes the original code
} 

Let's write a function that uses this modifier:

function setContactInformation(string info) onlyOwner{
     contactInformation = info;    
 }  

Flow after the modifier is applied:

if (msg.sender != owner) throw;
contactInformation = info;

You can get more info in this section of Solidity docs

This style of coding is called Condition-Oriented programing (you may read a nice coverage by Gavin Wood).

  • what happens if there are multiple modifiers? Are the first modifier(s) underscores removed and only the last one gets to be replaced with the function's code? – Paul Berg Sep 22 at 23:05
2

This is a modifier. It's a form of source code roll up.

You use it by tagging a function with the name of the modifier, like this:

function doSomethingSensitive() onlyOwner {
  // do stuff
}

The _ tells how to merge the code. In this case, first the modifier code, then the function code.

So, it compiles.

function() ... {
  if (msg.sender != owner) throw;
  // do stuff
}

You're allowed to reverse that or do more:

modifier onlyOwner {
   // do before
   __
   // do after
}

but I don't recommend it as it introduces flow-control related security problems and head-scratchers in most situations.

You can think of "do after" as "may not make it this far" because the function might (of course) have other ideas, and may not continue as expected.

Hope it helps.

  • what happens if there are multiple modifiers? Are the first modifier(s) underscores removed and only the last one gets to be replaced with the function's code? – Paul Berg Sep 22 at 23:06

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