📝 variables entry to the guide.
parent
789ad9657f
commit
6d34100d67
|
@ -102,5 +102,71 @@ tuples, with the addition of concatenation (``+``) and duplication (``*``) opera
|
|||
[3, 6, 8][1] # returns 6
|
||||
"love" in ["love", "pizzas"] # returns true
|
||||
|
||||
To access an array value, the operator ``[]`` can be used.
|
||||
For instance, syntax ``[3]`` means: "give me the third element".
|
||||
Arrays can be nested, that's why the operator ``[]`` can take several arguments.
|
||||
As an example, let's consider the following syntax ``[1, 2, 3]``
|
||||
means: "give me the third element of the second element of the first element of my array".
|
||||
|
||||
.. code-block::
|
||||
:caption: array
|
||||
|
||||
[[1, 2], [3, 4]] [0, 1] # equals 2
|
||||
[[1, 2], [3, 4]] [0, 0] # equals 1
|
||||
[[1, 2], [3, 4]] [1, 1] # equals 4
|
||||
|
||||
Declaring variables
|
||||
-------------------
|
||||
Variables declaration is a fundamental feature of pratically all programming languages.
|
||||
Some use only mutable variables (like Python), and others allow the programmer
|
||||
to declare immutable variables (like C for instance).
|
||||
CCM offer two syntaxes for declaring variables:
|
||||
the ``var`` keyword is used to declare mutable variables, and the ``const``
|
||||
keyword declares immutable one.
|
||||
|
||||
Storing expression using variables
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
Variables are containers for storing expressions.
|
||||
To declare a variable, we use the keyword ``var``
|
||||
followed by the name of the variable as well as its value: ``var name = expr``.
|
||||
|
||||
Variables can be reassigned later using the syntax ``name = expr``, and they can be
|
||||
used everywhere an expression can be.
|
||||
|
||||
.. code-block::
|
||||
:caption: mutable variable declaration
|
||||
|
||||
var x = 37
|
||||
x # equals 37
|
||||
x = 7
|
||||
x # equals 7
|
||||
|
||||
|
||||
Immutability using constants
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
A constant is an immutable values storage similaire to classical variables.
|
||||
The fundamental difference between constants and variables is mutability:
|
||||
variables can be reassigned, constants cannot.
|
||||
If you try to change the value of a constant, an error will be raised.
|
||||
|
||||
|
||||
.. code-block::
|
||||
:caption: immutable variable declaration
|
||||
|
||||
const x = 37
|
||||
x # equals 37
|
||||
x = 7 # ILLEGAL
|
||||
|
||||
Dereferencing arrays
|
||||
~~~~~~~~~~~~~~~~~~~~
|
||||
Variables can contain any expression, and in particular it could store an array.
|
||||
To access array elements, the operator ``[]`` can be used directly after the variable name.
|
||||
|
||||
.. code-block::
|
||||
:caption: Array dereferencement
|
||||
|
||||
var x = [2, 4, 6]
|
||||
x[1] # equals 4
|
||||
|
||||
I
|
||||
|
||||
|
|
Loading…
Reference in New Issue