In Solidity, a fallback function is an external function with neither a name, parameters, or return values. It is executed in one of the following cases:
Only one such unnamed function can be assigned to a contract.
Let's see an example of calling a function in Solidity in the code snippet below:
pragma solidity ^0.5.12;// contract with fallback functioncontract A {uint n;function set(uint value) external {n = value;}function() external payable {n = 0;}}// contract to interact with contract Acontract example {function callA(A a) public returns (bool) {// calling a non-existing function(bool success,) = address(a).call(abi.encodeWithSignature("setter()"));require(success);// sending ether to Aaddress payable payableA = address(uint160(address(a)));return(payableA.send(2 ether));}}
pragma
package.A
that has a state variable n
, a function set()
that accepts a value and stores it in n
, and a fallback function.example
to interact with the contract A
. We call a non-existing function of contract A
(line 19) and then try to send ether
to the contract (line 24). A
. So, its fallback function will be invoked. false
, as sending of the ether
failed. Free Resources