Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

solidity
communitycreator

What are functions in Solidity?

Shubham Singh Kshatriya

Overview

A function is a block of code or a collection of statements compartmentalized together to perform a specific task. It takes an input, does some processing, and produces an output.

Function declaration

In Solidity, we can declare a function using the function keyword, followed by the function name, a set of function parameters wrapped inside (), function scope, return values, and the function body.

Syntax

function functionName(parameters) scope returns() {
    // body
}

Parameters

It specifies a list of parameters that are accepted by the function. It contains the type and the name of each parameter separated by a comma. It can be empty as well.

Scope

In Solidity, the scope can be any of the following:

  • private: The function can be accessed only from inside the contract.
  • internal: The function can be accessed from inside the contract as well as the child contracts that inherit it.
  • external: The function can be accessed only from outside the contract. Other functions of the contract cannot invoke it.
  • public: The function can be accessed from everywhere.

Return values

It specifies a list of values that are returned by the function. It is required only when we return some values from the function.

Pure and view functions

Solidity also specifies a type that defines the accessibility behavior of the function. It can be defined between function scope and return values:

  • A pure function doesn’t read or modify the variables of the state. The detailed information about pure functions can be found here.
  • A view function only reads but doesn’t modify the variables of the state. The detailed information about view functions can be found here.

Function invocation/calling

To execute a function, we need to call or invoke it. We need to pass the required parameters along with the function name.

Example

The example below shows how to declare a function in Solidity.

pragma solidity ^0.5.0;

contract HelloWorld {
  // declare state variable
  string message = "Hello World";

  // create a function to return message
  function getMessage() public view returns(string memory) {
    return message;
  }
}
Example of the solidity function

Explanation

  • Line 3: We create a contract HelloWorld.
  • Line 5: We declare a state variable message.
  • Line 8: We create a function getMessage() that returns the value of the message.

RELATED TAGS

solidity
communitycreator

CONTRIBUTOR

Shubham Singh Kshatriya
RELATED COURSES

View all Courses

Keep Exploring