-7

Say I'm assigning codes to ASCII chars, where code 1 is assigned to the ASCII value 0, the NUL char, and so on. I'm doing this iteratively, currently with i+++1, that is:

for (int i = 0; i < 256; i++) {
    // assign code i++ +1
    arr[i].code = i++ +1;
}

If I were to use ++i instead, would that suffice?

  • 4
    Please show the actual code; not a vague comment in an otherwise empty loop. –  Nov 04 '16 at 06:11
  • @Danh Absolutely it's not. For bonus points, you could compare and contrast with preincrement (`++i+1`). – Edward Thomson Nov 04 '16 at 06:11
  • 1
    @EdwardThomson I know `(++i+1)` is valid statement, but I hadn't know about maximal munch strategy. The only thing I can find is this link http://stackoverflow.com/questions/7233317/3-plus-symbols-between-two-variables-like-ab-in-c, which said _The ANSI standard specifies_, is it said in ISO C? – Danh Nov 04 '16 at 06:21
  • 2
    @Danh Yes, it's in the C11 specification in section 6.4 paragraph 4: *"If the input stream has been parsed into preprocessing tokens up to a given character, the next preprocessing token is the longest sequence of characters that could constitute a preprocessing token."* and an example is given in paragraph 6: *"The program fragment `x+++++y` is parsed as `x ++ ++ + y`, which violates a constraint on increment operators, even though the parse `x ++ + ++ y` might yield a correct expression."* – user3386109 Nov 04 '16 at 06:34

4 Answers4

2

This might help

y = i+++x -> Add x to current value of i and assign the result to y and then increment value of i

y = ++1 -> increment i by 1 and assign the result to y

1

I would prefer to write that i++ + 1. But yes, ++i has the same effect and value asi+++1.

The latter logically does more work to arrive at the result, though: it keeps the old value ofi, increments i, adds one to the old value and yields the sum as result. The preincrement operator just increments i and uses its new value as result.

Technically both should compile to basically the same code given an optimising compiler.

1

Yes. They are the same.

++ bounds tighter than + so the expression is evaluated from left to right as

s = (i++) + 1

which can further be expanded as

s = i + 1
i = i + 1

On the other hand, s = ++i does the same task. It can be expanded as

i = i + 1
s = i

It is preferred that you use the second version because it is more readable and extensible. But I don't think there will be a difference in speed.

Confuse
  • 5,646
  • 7
  • 36
  • 58
0

Yes, i+++1 and ++i will both evaluate to the value of i plus 1, and will both leave i incremented by 1.

It's an odd way to do it, is there something wrong with just doing:

for (int i = 1; i < 256; i += 2)

Anyone reading your code later would prefer the latter, I believe.

Will
  • 1
  • 2