This series will provide answers to the list of Solidity interview questions that were published by RareSkills.
A modifier executes code before and/or after the modified function’s logic is executed. When a modifier is specified on a function, it is invoked when the function is called and passes execution control to the function where _;
is found. Modifiers are commonly used as access control mechanisms and allow for precondition and postcondition checks.
// SPDX-License-Identifier: MIT
pragma solidity 0.8.24;
// SimpleAccessControl demonstrates basic access control mechanisms
contract SimpleAccessControl {
address public owner;
// Modifier to restrict function access to the contract's owner
modifier onlyOwner() {
// This check will run before the `changeOwner` logic is executed
require(msg.sender == owner, "Caller is not the owner");
// This will execute the `changeOwner` logic.
_;
}
// Constructor sets the deploying address as the contract's owner
constructor() {
owner = msg.sender;
}
// Function to change the owner, restricted to the current owner
function changeOwner(address newOwner) public onlyOwner {
owner = newOwner;
}
}
The _;
syntax in a Solidity modifier is a placeholder that represents the point at which the modified function’s code is executed.
For instance,
_;
is placed at the beginning of a modifier, the function’s code runs before any other code in the modifier._;
is placed at the end, the modifier’s code will run before the function’s code.