0

I could just leave well enough alone here, but I'm curious. In this code, each byte in "wordbytes" is set individually from 0 to 1, ... 3. But why does it start at wordbytes[0], if "i++" is in the brackets? Doesn't this tell solidity we want to change the byte with the index of "i + 1", which would be 1 the first time around - aka the second byte?

bytes wordbytes = new bytes(4);
uint public i;


function setbyte(uint8 _utf8) public {
    wordbytes[i++] = byte(_utf8);                          

}

Doing the code in the following way - in which "i" is incremented after the byte is set - works the same:

bytes wordbytes = new bytes(4);
uint public i;


function setbyte(uint8 _utf8) public {
    wordbytes[i] = byte(_utf8);
    i++;                  

}

What tells solidity to increment "i" after "wordbytes[i]" is set in the first example?

3

The placement of the ++ is what determines that it will occur after.

If you want the i to be incremented before it is evaluated, you put the ++ before it.

So

  wordbytes[i++]

Uses the old value to access the wordbytes array, then increments it after.

  wordbytes[++i]

Increments it first, then accesses the array.

1

There you have answered yourself.

Doing the code in the following way - in which "i" is incremented after the byte is set - works the same :

The two scripts you have shown does the same thing because i++ increments the value of i after the current statement is executed.

This is not only the Solidity thing but is of almost all of the major programming languages convention. The incremental operators ++i and i++ are respectively increase value of i before and after the statement in which they are used.

If you want to increase the value of i beforehand use ++i.

wordbytes[++i] = byte(_utf8);

This is same as:

i++ // or ++i or i=i+1
wordbytes[i] = byte(_utf8);

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.