Recent Changes - Search:

Oktatás

* Programozás 1
  + feladatsor
  + GitHub oldal

* Szkriptnyelvek
  + feladatsor
  + quick link

Teaching

* Programming 1 (BI)
  ◇ exercises
  ◇ quick link

teaching assets


Félévek

* 2025/26/2
* archívum


Linkek

* kalendárium
   - munkaszüneti napok '20
* tételsorok
* jegyzetek
* szakdolgozat / PhD
* ösztöndíjak
* certificates
* C lang.
* C++
* C#
* Clojure
* D lang.
* Java
* Nim
* Nim2
* Scala


[ edit | logout ]
[ sandbox | passwd ]

increment a variable

Similar to Python.

nim> var x = 0
nim> ++x
Error: undeclared identifier: '++'
nim> x++
Error: expression expected, but found '[EOF]'

++x and x++ won't work. What can you use instead?

var x = 0

x += 1
echo x    # 1

x += 2
echo x    # 3

inc(x)
echo x    # 4

x = 10
echo x    # 10

x -= 1
echo x    # 9

x -= 4
echo x    # 5

dec(x)
echo x    # 4

More examples:

var a = 0

inc(a)
echo a        # 1

a.inc()
echo a        # 2

a.inc
echo a        # 3

a.inc(5)
echo a        # 8

How does inc() work?

By default, arguments are passed by value (like in C), i.e. a copy is made about the argument. inc() modifies the variable it received, which means that inc() must receive the variable by reference. Here is how to do it in Nim:

Nim: pass by reference
#include <stdio.h>

void my_inc(int *p)
{
    *p += 1;
}

int main()
{
    int x = 0;

    my_inc(&x);

    printf("%d\n", x); // 1

    return 0;
}
# here "var" means that the argument is passed by reference
# if you modify it, it'll be visible on the caller's side
# You can think of "n" that it's an alias on the "x" variable.
proc my_inc(n: var int) =
  n += 1

var x = 0

my_inc(x)

echo x    # 1

In Nim how you pass an argument to a procedure (by value or by reference) is indicated on the formal parameter list of the procedure.

In C, you decide it on the caller's side. Either you pass a variable or its memory address.

Exercise

Improve my_inc() so that it can accept the value of incrementation. Expected behaviour:

var x = 0

x.my_inc()
echo x      # 1

x.my_inc(4) # !!! new thing !!!
echo x      # 5

my_inc(x)
echo x      # 6

x.my_inc
echo x      # 7
Cloud City

  

Blogjaim, hobbi projektjeim

* The Ubuntu Incident
* Python Adventures
* @GitHub
* heroku
* extra
* haladó Python
* YouTube listák


Debrecen | la France


[ edit ]

Edit - History - Print *** Report - Recent Changes - Search
Page last modified on 2026 April 05, 22:46