4

I understand that the difference is that, while neither may change the state, view may read the state and pure may not. I also understand that it's useful to distinguish possibly state-changing functions from those guaranteed not to change the state.

My question is, why is it useful to indicate that a function won't even access state? Why doesn't view suffice?

3
  • Probably in order to allow a higher level of compiler optimization for pure functions. And by the way, you could just as well ask the same question about view (i.e., why is it useful to indicate that a function won't change state?). Aug 25, 2018 at 10:53
  • Oh, and another reason - it's there to protect you from doing things you didn't initially intend to. By declaring a pure function, you "remind" yourself (and others), that this function has no intention of reading state variables, nor to invoke any other function which reads state variables. It's kinda like const in C/C++. If you later decide to change functionality, you get this compilation error reminding you of your original design intentions. Aug 25, 2018 at 11:01
  • Well the other question you propose - why is it useful to indicate a function won't change state - is both covered well elsewhere and more obvious: changing state costs money.
    – Joseph
    Aug 26, 2018 at 3:46

2 Answers 2

7

If a function is pure, then no matter how many times you call it, if you pass the same parameters, it will always return the same value(s).

Example:

function pureFunction(uint a) pure returns(uint){
    return a + 5;
}

will always return 6 if you pass 1 as parameter a.

However, if the function is view, it's reading from the state, which may have changed since the last time you called it.

Example:

uint B = 5;

function viewFunction(uint a) view returns(uint){
    return a + B;
}

will also return 6 if you pass 1 as parameter a. But if another function modifies the value of B, then next time you call viewFunction(1), it will return something different.

1
  • I do not think that pureFunction example is a pure function
    – Yilmaz
    Dec 5, 2022 at 1:49
-1

I find the answer above confusing. It really boils down to this:

Pure does (can) not access state only memory/stack

View can access state but not make changes to it, just query (+ ETL).

No state changes in a transaction call means no gas cost, we're letting the compiler know that so we can get the right behaviour (sendTx vs call) after deployment.

2
  • 3
    This doesn't answer the question. The dude says he already knows the difference between pure and view. Aug 25, 2018 at 10:55
  • And what's the common denominator? "no state modifications possible". Aug 25, 2018 at 11:05

Your Answer

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

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