Trusted answers to developer questions

What is _; in Solidity?

Free System Design Interview Course

Many candidates are rejected or down-leveled due to poor performance in their System Design Interview. Stand out in System Design Interviews and get hired in 2024 with this popular free course.

In Solidity, there is the uncommon instruction _;.
_; is used inside a modifier to specify when the function should be executed.

A modifier is a piece of code that manipulates the execution of a function.

The _; instruction can be called before and after the call of the function. So, we can put _; inside the modifier when we want to execute the function, e.g., after checking if something is correct.

Examples

Let’s look at some common usage of the _; instruction.

Check before execution

In this case, we call the instruction after we check that the address of the caller is not equal to 0xAb5801a7D398351b8bE11C439e05C5B3259aeC9B.

Note: If the check fails, the function will not be executed at all.

pragma solidity ^0.5.0;
contract HelloWorld {
modifier notForVitalik() {
require(msg.sender != 0xAb5801a7D398351b8bE11C439e05C5B3259aeC9B, "Not owner");
_;
}
bytes32 message;
constructor (bytes32 myMessage) public {
message = myMessage;
}
// this function is NOT for vitalik
function getMessage() notForVitalik public view returns(bytes32) {
return message;
}
}

Check after execution

We can run the function and make something else afterwards. This is useful in certain cases.

In this case, we emit the event emitGotMessage after we call the function.

pragma solidity ^0.5.0;
contract HelloWorld {
event gotMessage();
modifier emitGotMessage() {
_;
emit gotMessage();
}
bytes32 message;
constructor (bytes32 myMessage) public {
message = myMessage;
}
function getMessage() emitGotMessage public returns(bytes32) {
return message;
}
}

RELATED TAGS

solidity

CONTRIBUTOR

Dario Vincenzo Tarantini
Did you find this helpful?