Solidity Comments
Comments are notes written inside code for people to read. The compiler ignores them, so they never change what a contract does.
Line comments sit beside code
Each // starts a note that runs to the end of its line. The variable between the notes still holds its value.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;
contract CommentDemo {
// The player's score, set once here.
uint256 public score = 15; // Anyone can read this value.
}Block comments can span lines
A block comment opens with /* and closes with */. It can cover several lines at once.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;
contract CommentDemo {
/* The total below was counted
from the last practice game. */
uint256 public total = 20;
}Comments inside a function
A comment can sit inside a function body, next to the line it explains. The function still saves the value it receives.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;
contract CommentDemo {
uint256 public value;
function setValue(uint256 newValue) public {
// Save the number the caller sent.
value = newValue;
}
}Example
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;
contract CommentedBox {
// The score starts at zero.
uint256 public score = 0;
/* This function replaces the old
score with the caller's number. */
function setScore(uint256 newScore) public {
score = newScore; // The old value is gone.
}
}Key points
- Line comment: text after // is a note that ends at the end of the line.
- Block comment: text between /* and */ is a note that can span many lines.
- Use comments to explain why code exists, in plain words.
- Compiler: the tool that builds the code and skips every comment.
- Working code: comments can sit beside real code without changing its values.
In this example, a line comment explains the score variable, and a block comment explains the setScore function over two lines. The function saves the caller's number into score, exactly as it would with no comments at all. Calling setScore(30) makes score read back as 30.
Note
Deleting every comment from a file leaves a working contract with the same behaviour.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Remix IDE
Exercise
What happens to comments when a contract is compiled?