Fallback function in solidity

Fallback function in solidity

Have you ever thought about humans without names, how weird it will be if we don't have names. Assume how we call them and how they know that someone is calling them without announcing their name. That's the reason, all humans has names that uniquely identify them.

Same thing apply to functions, when we create functions, we generally name each and every function properly so that anyone get to know the purpose of the function. We never have thought about having a function without a name, without any input argument, without any return value. But this is possible in solidity and that function is known fallback function.

Let's understand when this function is used in solidity.

1. When function identifier does not match any of the available functions in a smart contract or if there was no data supplied at all.

 

pragma solidity ^0.4.20;

contract student{
string name;
function() public {
name="joe";
}
}

contract teacher{
function f(studentĀ  _std) public {
_std.call(0xabcdef01);
}
}

 

2. Whenever a particular contract receives plain Ether but function need to have payable keyword.

pragma solidity ^0.4.20;

contract seller{
function() public payable {
}
}

contract buyer{
function f(address _add) public {
seller(_add).send(10);
}
}

 

This function can't do much as only 2300 gas associated with it so should not add lengthy logic inside this.

No Comments

Post a Reply

Inquire Now
close slider