7

Sometimes ABAP drives me crazy with really simple tasks such as incrementing an integer within a loop...

Here's my try:

METHOD test.

  DATA lv_id TYPE integer.

  lv_id = 1.

  LOOP AT x ASSIGNING <y>.
    lv_id = lv_id+1.
  ENDLOOP.

ENDMETHOD.

This results in the error message Field type "I" does not permit subfield access.

Sandra Rossi
  • 11,934
  • 5
  • 22
  • 48
Ben
  • 245
  • 2
  • 6
  • 9

6 Answers6

24

You already answered the question yourself, but to make things a bit clearer:

variable + 1 

is an arithmetic expression - add 1 to the value of the variable.

variable+1

is an offset operation on a character variable. For example, if variable contains ABC, variable+1 is BC.

This can be especially confusing when dealing with NUMCs. For example, with variable = '4711', variable + 1 is evaluated to 4712, whereas variable+1 is '711' (a character sequence).

The error you saw occurred because it's not possible to perform the index operation on a non-character-like variable.

vwegert
  • 18,371
  • 3
  • 37
  • 55
15

You mean like:

ADD 1 to lv_id.

By the way, when you loop over an internal table, SY-TABIX has the loop counter.

Wladimir Palant
  • 56,865
  • 12
  • 98
  • 126
tomdemuyt
  • 4,572
  • 2
  • 31
  • 60
  • Just beware of loops within loops. Oh, and if you are looping with a `DO..TIMES x`, then the loop counter will be `SY-INDEX`. Yes, ABAP is a terribly inconsistent language. – Marius Oct 23 '13 at 15:47
  • 1
    SY-TABIX does not contain the loop counter, it contains the table index. These are often different values. For instance, if I write `LOOP AT messages INTO msg WHERE type = 'E'`, the first time the loop actually runs might be on the fourth row, and the value of sy-tabix will be 4. – Eric Jul 22 '14 at 18:21
8

Uh, I got it. It's the f****** spaces...

lv_id = lv_id + 1

works...

Ben
  • 245
  • 2
  • 6
  • 9
1

Simple

DATA : gv_inc type I .

place this statement in loop

gv_inc = gv_inc + 1 .

Android Genius
  • 224
  • 1
  • 6
1

from SAP NetWeaver Version 7.54 you can also use:

lv_id += 1.

Instead of

lv_id = lv_id + 1.

Happy coding!

Frontmaniaac
  • 221
  • 3
  • 14
0

If you are going to increment every loop cycle than you can directly get the table size.

describe table x lines data(lv_id). "Out side of the loop.