Loading...
Functions in solidity is all about visibility and behaviour.The visibility reffers to the functions like public,private,internal and external.Similarly behaviour refferes to the view,pure and payable in functions.
View function is used to read the state variables and do not modify after calling it.
here state variables reffer to the variables defined outside the view function.
by using view function one can only access the variables and do not modify it.
similarly one view function can call another view function only.
the get function is the default view function in solidity.
so let's understand view function
pragma solidity ^0.8.0;
contract viewcon{
uint public a=10;//these are the state variables
uint public b=2;
function viewfun()public view returns(uint){
return a+b;
}
}
Output:
//calling viewfun() function gives the output as:
0:uint256: 12
When you call the the above viewFun() function, observe that it is not going to create any transaction.
Why?
because making the transaction reffers to make changes in state of blockchain.Unless and until you make transaction it is not possible to make changes in the state of blockchain.So view function exactly do the same which it has promise to us that is it will no modify the state of blockchain.
function F1() public view returns(string memory){
return "Hello I am F1";
}
function checkF1()public view returns(string memory){
return F1();
}
Output:
0:string: Hello I am F1
When you call checkF1 function above output you will get.
So to call F1() in checkF1 we need to define both functions as view otherwise it will give the error.
Pure functions are like view functions but additionaly it cant read the state variables like view functions.
They are only able to do the computation inside Pure function or the parameters passed to it.
pragma solidity ^0.8.0;
contract PureCon{
function add() public pure returns(uint sum){
uint a=1;//these are the local variables
uint b=2;
sum=a+b;
}
}
Output:
0:uint256: sum 3
Instead of declaring local variable inside pure function we can pass the parameters also to add() function while calling it.
Similarly to View functions Pure functions can call other Pure functions only.