1. What are initial values for different data types?
What are the initial/zero values for different data types in Solidity?
In Solidity docs they are called initial values:
-
Value Types
-
boolean
:false
-
string
:""
-
int
:0
-
uint
:0
-
fixed
:0.0
(presumably; this type is not fully supported) -
enum
: the first element of the enum -
address
:0x0
-
function
-
internal
: empty function, returning initial values (if return is needed) -
external
: function that throws when called
-
-
-
Reference Types
-
mapping
: empty mapping -
struct
: a struct where all members are set to initial values -
array
- dynamically-sized:
[]
- fixed-sized: an array of the fixed size where all elements are set to initial values
- dynamically-sized:
-
When you use the delete
keyword it will assign the initial value to the variable, except for mappings, where it doesn't have any effect. For structs the delete
keyword will recurse into the members, unless they are mappings.
2. When to use payable
keyword?
Presence of payable
modifier means it can process transactions with non zero Ether value.
type
address payable
You can use transfer
and send
on address payable
→address payable
declared address can receive ether
function payable
function with payable modifier can receive ether (from msg.value or from other contract’s function)
- constructor function
Used when you need to send ether in deployment.
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.0;
contract Sample {
address owner;
uint value;
constructor() payable {
owner = msg.sender;
value = msg.value;
}
function getInfo() public view returns(address, uint) {
return (owner, value);
}
}
- normal function
Used when you use msg.value
or send ether in function
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.0;
contract Sample {
mapping(address => uint256) balance;
function deposit() public payable {
balance[address(msg.sender)] += msg.value;
}
function getBalance(address _address) public view returns(uint){
return balance[_address];
}
}
-
recieve
&fallback
function
If I send some ether to Sample
by other contract, receive
wll handle and automatically put value into contract’s balance.
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.0;
contract Sample {
receive() external payable {
}
function getBalance() public view returns(uint){
return address(this).balance;
}
}
3. What does uint8
actually mean?
uint8
means unsigned integers of size8 which is range from 0 to 255. In addition int8
is range of -128 to 127.
4. Is returned variable can be used inside function?
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.0;
contract Sample {
function add(uint[] calldata _arr) external pure returns(uint sum){
uint i;
while(i < _arr.length) {
sum += _arr[i];
i++;
}
return sum;
}
}
Yes, I think returned variable can also be tread same as function parameters.
Top comments (0)