8

Example :

pragma solidity ^0.4.8;

contract X{

    uint amount;

    function X() {
        amount = amount + msg.value;
    }
}

Here Constructor X() is not payable. Should I change it to payable because of using msg.value ?

4
  • Yes, I think this was changed in Solidity 0.4.x – Mikko Ohtamaa Feb 17 '17 at 8:07
  • 2
    No, it's not mandatory, but it will always be 0, because the contract will throw an exception if there is any value sent with it. – Tjaden Hess Feb 17 '17 at 22:33
  • What will always be zero? The amount, or msg.value? @TjadenHess – vonGohren May 4 '17 at 21:20
  • Both. msg.value will always be zero, because any nonzero value will cause an error. ammount will be zero because it is impossible to add anything to it – Tjaden Hess May 4 '17 at 21:25
2

Not mandatory, but as Matthew notes, it would be useless to leave it out of the function that should be receiving ether.

msg.value gets passed around internally.

Browser Solidity is aware that we don't have a problem in the code below. It's not warning about the presence of msg.value inside a function that itself isn't payable.

If the logValue() function is changed to public, then Browser Solidity warns that there might be an oversight.

enter image description here

1

Having just tried it in browser-solidity, it will warn you, but it will not stop you.

That said, I'm not sure what use it would have other than calling it through a different, payable function. browser-solidity doesn't have a way to send amounts, it seems. Can anyone test if that works?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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