FinMartinez
FinMartinez

Reputation: 35

Trouble understanding increment operators with arrays in C

I'm having trouble wrapping my head around a concept in C regarding the use of the operator ++ and arrays. I know enough that ++ will increment a value, but I'm running into a code snippet that does not make any sense to me:

  while((c = getchar()) != EOF)
  {
    if(c < NUM_CHARS)
    {
      thisval = ++freqarr[c];
      if(thisval > maxval)
      {
        maxval = thisval;
      }
    }

the line thisval = ++freqarr[c]; does not make a lot of sense to me. Does it mean that thisval adds an additional index or value to the array?

I'm still new to C, so I'm not sure if this is common in C or not, if it's not or looked down upon, please let me know.

Upvotes: 1

Views: 56

Answers (3)

dbush
dbush

Reputation: 223699

The prefix ++ operator increments its operand, and the resulting expression has the incremented value.

So this line does two things:

  • It increments the value of freqarr[c] which is a member of an array
  • It assigned the incremented value of freqarr[c] to thisval

Upvotes: 0

Keith Thompson
Keith Thompson

Reputation: 263217

I presume that c is defined as an int and freqarr is defined as an array. (It's generally best to include a Minimal, Reproducible Example in your question).

The prefix ++ operator increments an object and yields the incremented value. freqarr[c] is an object. The fact that it happens to be an element of an array is not relevant here. It works the same way as it would if it were applied to a simple named variable.

Note that the indexing operator [] binds more tightly than ++, so the expression ++freqarr[c] is equivalent to ++(freqarr[c]).

Upvotes: 0

Nate Eldredge
Nate Eldredge

Reputation: 57997

Prefix ++ has lower precendence than [], see https://en.cppreference.com/w/c/language/operator_precedence. So this is equivalent to thisval = ++(freqarr[c]);. It takes the cth element of the array, and increments that element, then assigns the new value to thisval. Just like:

freqarray[c] = freqarray[c] + 1;
thisval = freqarray[c];

Upvotes: 1

Related Questions