Variable assignment in contract

How do I reassign a variable in a contract? This is something similar to what I want to achieve

let x: int = 0
if(y < 100)
    x = 1
else
    x = 2
1 Like
contract C =
  entrypoint f(y: int) : int=
    let x = 0
    if(y < 100)
      let x = 1
      x
    else
      let x = 2
      x

is a valid contract, but the code doesn’t make much sense… It is better written:

contract C =
  entrypoint f(y: int) : int=
    if(y < 100)
      1
    else
      2

Do you have a more realistic case perhaps? Reassigning a variable isn’t very interesting in itself!

1 Like

Thanks for that,

I’m getting this error when reassigning,
parse_error: Unexpected token '='.

Also, to give you a more realistic feel of the use-case, I need to use the variable x for computing a new variable, say z which will eventually be returned. So basically, this is what the code will kind of look like:

contract C =
  entrypoint f(y: int) : int=
    let x: int = 0 
    if(y < 100)
       x = 1
    else
       x = 2
    let z: int = x + 120 // an arithmetic compuation with x, y and some state variables
    z

Also, I tried this -

contract C =
  entrypoint f(y: int) : int=
    let x: int = 0 
    if(y < 100)
       let x = 1
    else
       let x = 2
    let z: int = x + 120 // an arithmetic compuation with x, y and some state variables
    z

Then I’m not getting the parse_error as above but getting this -
type_error: Let binding must be followed by an expression

Yes, just like the compiler suggests, let x = 1 is not an expression, it is just a binding…

let x = 1
x

is an expression (though a silly one).

In this case I’d suggest:

let x: int = if(y < 100) 1 else 2
x * y + z

Thanks for that, it works! :slight_smile: