2

I was reading a book on solidity, the array was defined as int[5] age= [int(10),20,30,40,50]

When data type int was declared at the start then why it is declared again in the array with 10?

1 Answer 1

3

Solidity determines the type of array literal ([int(10),20,30,40,50]) as the smallest type all the elements could be implicitly converted into. Here element types are: int, uint8, uint8, uint8, uint8, so the smallest type all elements may could be converted into is int. So the type of array literal is int[5].

If you omit int(...), then types of all the elements would be uint8, thus the whole literal would have type uint8[5] which is incompatible with the type of the variable this value is about to be assigned to.

See documentation for details.

2
  • Then what is the purpose of declaring data type before array name? Like in this case ` int[5]` so what will this int do?
    – uzair kath
    Apr 24, 2020 at 17:47
  • 1
    int[5] is the type of the variable age, not the type of the expression to the right from the equals sign. The type of an expression is determined by the expression itself and should be compatible with the type of a variable the value of this expression is being assigned to. Apr 27, 2020 at 8:24

Your Answer

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

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