0

I just found that when I do 5/2 with assignment operator, it does not give any error immediately and just give the result as 2 instead of 2.5. Would you please let me know why it is ?

// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.7.0 < 0.9.0;

contract Practice {
   uint a = 5;
   function assignment() public returns(uint){
    a /= 2 // no error 
    return(a) // it returns 2 instead of 2  
   }
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.7.0 < 0.9.0;

contract Practice {
   uint public a = 5/2; // error occured
}

and One more question , when I do declare public to variable, will it be private ?

// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.7.0 < 0.9.0;

contract Practice {
   uint a; // Does it become private?
}

2 Answers 2

1

Case 1:

You are just doing an integer division here, as solidity cannot do anything else than that... So 5/2 = 2. The true result is 2.5 yes, but if you only deal with integers you scratch the decimal part and the result is 2.

Case 2:

uint public a = 5/2; // error occured

This fails because 5/2 is evaluated at compilation time. The compiler code can evaluate this to a rational number (2.5) but will throw an error because 1) solidity only deals with integers and 2) Even though it could convert it to integer (2) and compile it, it would be a terrible idea as it would allow the compiler would silently change the value for something different from what you wrote. It's much better to throw an error right here.

Finally :

when I do declare public to variable, will it be private ?

From the documentation :

internal

Those functions and state variables can only be accessed internally (i.e. from within the current contract or contracts deriving from it), without using this. This is the default visibility level for state variables.

So, no they are not public by default but internal. The only difference with private is that internal allows derived contract to access that variable while private doesn't.

0

The first question has been answered, but the second isn't fully explained.

Keep in mind that everything on the blockchain is public and the private variable are only private to other smart contracts and contract calls, but the data itself is not encrypted and is visible on the blockchain. Yes, access won't be ass simple as a contract call or query, but it is there and can be viewed with transaction inspection via the bytes of the tx.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.