Smart Contract Language Solidity Tutorial Series 1-Type Introduction

Source: Internet
Author: User
Tags arithmetic arithmetic operators bitwise bitwise operators integer division truncated

Now the solidity Chinese document, either the translation is too bad, or too old, decided to re-translate.
In particular, criticized the Geek Institute named "solidity official document Chinese version of" translation, machine translation is better than it, we still do not look.

Write in front

Solidity is the Ethereum Smart Contract programming language, you should know about Ethereum and smart contracts before reading this article.
If you don't understand, it's recommended that you look at Ethereum first.
Solidity tutorial will be a series of articles, this article is the first: Describes the variable types of solidity.
For a complete list of articles in the solidity series, see Category-solidity.

The first half of this article is a reference to the solidity official document (currently the latest version: 0.4.20) for translation, and the latter part is the use of the actual contract code instance description type.

Type

Solidity is a statically typed language, meaning that each variable (local or state variable) needs to specify the type of the variable at compile time (or at least the type can be pulled out). Solidity provides some basic types that can be used to combine into complex types.

The solidity types fall into two categories:

    • Value type-The value is always copied when the variable is assigned or passed.
    • Reference type (Reference Types)
Value type

value types include:

    • Boolean type (Booleans)
    • Integral type (integers)
    • Fixed-length float (fixed point Numbers)
    • Fixed-length byte array (fixed-size byte arrays)
    • Rational number and integral type constant (rational and integer literals)
    • string constant (string literals)
    • hexadecimal constant (hexadecimal literals)
    • Enumeration (Enums)
    • function type (functions Types)
    • Address Type
    • Address Constants (Addr literals)

      There is a separate post for the function type and address type, please click View.

Boolean type (Booleans)

Boolean (BOOL): The possible values are constant values true and false.

The supported operators for Boolean types are:

    • ! Logical Non-
    • && Logic and
    • || Logical OR
    • = = equals
    • ! = does not equal

Note: Operators && and | | is a short-circuit operator, such as f (x) | | G (Y), when f (x) is true, g (Y) is not continued.

Integral type (integers)

int/uint: Represents a signed and unsigned integer with a different number of digits. Supports keyword uint8 to uint256 (with 8 steps),
The uint and int by default correspond to uint256 and int256.

Supported operators:

    • Comparison operators: <=, <, = =,! =, >=, > (return Boolean: TRUE or False)
    • Bitwise operators: &,|,^ (XOR), ~ (bitwise inverse)
    • Arithmetic operators: +,-, unary operations-, unary operations +,*,/,% (take remainder), * * (Power), << (left shift), >> (right Shift)

Description

    1. Integer division is always truncated, but if the operator is literal (the literal is later), it is not truncated.
    2. Integers except 0 throw exceptions.
    3. The positive or negative of the result of the shift operation depends on the number left of the operator. x << y and X *y are equal, x >> y and x/2\y are equal.
    4. Negative shifts cannot be performed, that is, the number on the right of the operator cannot be negative, or a run-time exception is thrown.

Note: In solidity, the right shift is equal to the equivalent, so the right shift is a negative number, and the downward rounding will be 0, rather than the infinite negative decimals in other languages.

Fixed-length float (fixed point Numbers)

Note: fixed-length floating-point solidity are not fully supported, and can be used to declare variables, but they cannot be used to assign values.

Fixed/ufixed: Represents signed and unsigned stationary bit floating-point numbers. The keywords are ufixedmxn and ufixedmxn.
M represents the number of bits that this type takes up to 8 steps, which can be 8 to 256 bits.
N represents the number of decimal points, which can be between 0 and 80

Supported operators:

    • Comparison operators: <=, <, = =,! =, >=, > (return Boolean: TRUE or False)
    • Arithmetic operators: +,-, unary operations-, unary operations +,*,/,% (take remainder)
      Note: Unlike most languages, float and double,M is the fixed number of digits that represent the entire number, including the integer and fractional parts. Therefore, when a small number (m small) is used to represent a floating-point number, the sub-chapters occupy almost the entire space.
Fixed-length byte array (fixed-size byte arrays)

Keywords are: bytes1, Bytes2, Bytes3, ..., bytes32. (Increment by step 1)
BYTE represents Bytes1.

Supported operators:

    • Comparator: <=, <, = =,! =, >=, > (return bool)
    • Bitwise operators: &, |, ^ (bitwise XOR), ~ (bitwise inverse), << (left shift), >> (right Shift)
    • Index (subscript) Access: If X is Bytesi, when 0 <= K < I, then X[k] returns the K-byte (read-only).

A shift operation is similar to an integer, and the result of a shift operation depends on the number of left side of the operator and cannot be negatively shifted.
If can -5<<1, can not 5<<-1

Member variables:
. Length: Indicates the length of this byte array (read-only).

Variable length (Dynamically allocated size) byte array (dynamically-sized byte arrays)
    • Bytes: Dynamically allocated size byte array, see arrays, not value type!
    • String: Dynamically allocate size UTF8 encoded character type, see arrays. Not a value type!

Based on experience:
Bytes is used to store byte data of arbitrary length, and string is used to store arbitrary length (UTF-8 encoded) string data.
If the length can be determined, try to use a fixed length, such as byte1 to Byte32, because it is more space-saving.

Rational number and integral type constant (rational and integer literals)

Some people have translated literals into literal quantities.

Integer constants are composed of a series of 0-9 numbers, 10 binary representations, such as: 8 binary is not present, and the preceding 0 is invalid in solidity.

10 Decimal constant (decimal fraction literals) with one ., in . The two sides have at least one number, valid for example:1., . 1 and 1.3.

Scientific symbols are also supported, the cardinality can be decimal, the exponent must be an integer, valid representations such as: 2e10, -2e10, 2e-10, 2.5e1.

The numeric constant expression itself supports arbitrary precision, that is, it can not be an operation overflow, or division truncation. But when it is converted to the corresponding very mass type, or they are calculated with a very good amount, there is no guarantee of accuracy.
such as: (+ 1)-800 of the result is 1 (uint8 whole class), although the intermediate results have exceeded the computer word length. In addition: *. 5 The result of 8** is 4, although there are non-xxx involved in the operation.

As long as the operand is xxx, an integer-supported operator applies to an integer constant expression.
If the two operands are decimals, bitwise operations are not allowed, and the exponent cannot be a decimal number.

Attention:
Solidity has a numeric constant type for each rational number. Integer constants and rational number constants are subordinate to numeric constants. The results of all numeric constant expressions are numeric constants. So 1 + 2 and 2 + 1 all belong to the same rational number constant 3

Warning:
Integer constant division, which is truncated in earlier versions, can now be converted to a rational number, such as a value of 5/2 of 2.5

Attention:
A numeric constant expression that, once it contains a constant expression, is converted to a very literal type. The result of the expression in the following code is considered to be a rational number:

uint128 a = 1;uint128 b = 2.5 + a + 0.5;

The above code compilation does not pass because B is considered a decimal type by the compiler.

String constants

String constants are strings ("foo" or "bar") that are caused by single or double quotation marks. The string is not like the C language, contains a terminator, and the string "foo" is only three bytes in size. As with integer constants, the length type of a string can be variable. Strings can be implicitly converted to byte1,... byte32, if appropriate, will also be converted to bytes or string.

String constants support escape characters, such as \n,\xnn,\unnnn. Where \xnn represents a 16 binary value and eventually converts the appropriate byte. Instead, \UNNNN represents a Unicode encoded value that is eventually converted to a sequence of UTF8.

hexadecimal constant (hexadecimal literals)

A hexadecimal constant, preceded by the keyword hex, followed by a string wrapped in single or double quotation marks, with the contents of a hexadecimal string, such as Hex "001122FF".
Its value is represented by the binary.

Hexadecimal constants are similar to string constants and can also be converted to byte arrays.

Enumeration (Enums)

In solidity, enumerations can be used to customize the type. It can display conversions that are converted to integers, but cannot be implicitly converted. The displayed transform checks the range of values at run time and, if not, causes an exception. The enumeration type should have at least one member. The following is an example of an enumeration:

pragma solidity ^0.4.0;contract test {    enum ActionChoices { GoLeft, GoRight, GoStraight, SitStill }    ActionChoices choice;    ActionChoices constant defaultChoice = ActionChoices.GoStraight;    function setGoStraight() {        choice = ActionChoices.GoStraight;    }    // Since enum types are not part of the ABI, the signature of "getChoice"    // will automatically be changed to "getChoice() returns (uint8)"    // for all matters external to Solidity. The integer type used is just    // large enough to hold all enum values, i.e. if you have more values,    // `uint16` will be used and so on.    function getChoice() returns (ActionChoices) {        return choice;    }    function getDefaultChoice() returns (uint) {        return uint(defaultChoice);    }}
Reference documents

Solidity official documents-type

In-depth blockchain-the system learns blockchain to create the best blockchain technology blog.

Smart Contract Language Solidity Tutorial Series 1-Type Introduction

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.