0
pragma solidity ^0.4.0;

contract MyFirstContract {
    uint private age;

    function setAge(uint newAge) {
        age = newAge;
    }

    function getAge() returns (uint) {
        return age;
    }
}

When I create the contract in remix and then set for example the number 3 to the variable age, then when I call getAge() it shows nothing. But if I add "constant" like:

function getAge() constant returns (uint) {
    return age;
}

then it works. I saw some video that the same code was working without declaring "constant", so I dont really undestand why it is not working for me.

2

There are two ways to invoke a function in a smart contract:

  1. You can send a transaction. A transaction gets sent to the network and gets mined as part of a block. It's verified by all the nodes in the network.
  2. You can call a function. This does not send anything to the rest of the network; a call is executed locally on the node you're connected to. You get back the return value of the function, but otherwise the call has no side effects. If it transferred ether or changed a state variable, those changes are just thrown out. The advantage of a call is that it's fast and free (no need to pay gas).

Remix decides whether to send a transaction or make a call based on whether the function is marked as mutating state or not. view/constant tells the compiler and then Remix that you're not mutating state, so this function can be called instead of sending a transaction.

This explains why Remix treats the function differently depending on whether you use the constant modifier. The final piece of the puzzle is that transactions do not have return values. If you invoke getAge as a transaction, the code will run, but you won't get back the return value.

Because of these differences, it's a best practice to always mark functions that don't modify state as view (a better alias for constant). That makes the function fast, free, and able to return a value to you.

0

See here for information on getters:

The compiler automatically creates getter functions for all public state variables.

because your age variable is declared private, getter functions aren't created automatically and this could be why your getAge function needs to be declared as constant (or better, as view) in order to access the state.

Note that it is good practice to declare visibility for all functions - you're probably getting errors about 'no visibility specified. Defaulting to 'public'' in your compiler. see Function Calls in the solidity docs for info.

  • This makes no sense. getAge is a function in this contract. Of course it can access private state variables. – user19510 Jan 28 '18 at 19:34

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.