Stage 96: Shortcut Operators :++ / :--

Follow the development of the SharpBASIC compiler and share your thoughts and ideas.
Locked
User avatar
frank
Site Admin
Posts: 40
Joined: Sun Nov 21, 2021 12:04 pm
Location: Netherlands
Contact:

Stage 96: Shortcut Operators :++ / :--

Post by frank »

At this stage the operators :++ (increment) and :-- (decrement) were added. These operators always start with a colon to avoid ambiguity.

Example of an increment statement:

Code: Select all

my_value:++;
will increment my_value by 1.

Some pointer specific built-in procedures accept a trailing increment / decrement operator:

Code: Select all

stob(my_ptr, my_byte);
my_ptr:++;

' can be shortened to:

stob(my_ptr, my_byte):++;
In the following example the increment operator advances the pointer used with bya() to read a series of string bytes. Increment is 1 byte because bya() assigns to an uint8 (unsigned byte) datatype:

Code: Select all

dim text:str = "A brave new world";
dim p:ptr;
dim b:uint8;

main do
  p = sadd(text);
  loop do
    b = bya(p):++;
    if b == 0 do break; end
    print(b);
  end
end
In combination with procedures, the operators are only valid if the pointer argument is not an expression.

In the next example the increment/decrement operators are used to convert integer to alphanumeric (itoa). Note the built-in function vstr() which converts a fixed-length string to a variable-length string:

Code: Select all

func itoa(value:int, base:int):str
  const symbols = "ZYXWVUTSRQPONMLKJIHGFEDCBA9876543210123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
  dim is
    result:str*21;
    ptr0, ptr1, ptr2:ptr;
    tmp_value:int;
    tmp_char:uint8;
  end
do
  ptr1 = sadd(result);
  stob(ptr1, 0);

  when base is not 2 to 36 do jump @result; end

  ptr0 = sadd(symbols);
  ptr2 = ptr1;

  loop do
    tmp_value = value;
    value = value / base;
    stob(ptr1, bya(ptr0 + (35 + tmp_value - value * base))):++;
    while value <> 0;
  end

  ' apply negative sign
  if tmp_value < 0 do
    stob(ptr1, "-");
  end

  stob(ptr1 + 1, 0);

  loop do
    while ptr2 < ptr1;
    tmp_char = bya(ptr1);
    stob(ptr1, bya(ptr2)):--;
    stob(ptr2, tmp_char):++;
  end

  @result;
  ' return variable string
  itoa = vstr(result);
end
Last edited by frank on Wed Mar 09, 2022 10:55 pm, edited 6 times in total.
Keep it simple!
Locked