1

Is there shorter/faster code in C for incrementing array?

void arrayIncrement(int array[], int size, int increment) {
    for (; size >= 0; size--) {
        array[size] += increment;
    }
}
3
  • 3
    I think any space you save will be at the cost of readability from this point. 5 lines is not significant. Commented Oct 3, 2020 at 13:58
  • If size is really the size of the array then you are invoking undefined behavior on the first iteration, by accessing one past the end. And if the caller always has to pass size - 1 then it's a very unconventional API Commented Oct 3, 2020 at 14:02
  • 2
    while(size--) array[size] +=increment; Commented Oct 3, 2020 at 14:04

1 Answer 1

3

Your code actually has undefined behavior because you increment array[size] which is the element beyond the end of the array.

Note also that size should have type size_t to allow for very large arrays on 64-bit systems.

You should either decrement size before incrementing the array element:

void arrayIncrement(int array[], size_t size, int increment) {
    while (size-- > 0) {
        array[size] += increment;
    }
}

Or increment the array pointer:

void arrayIncrement(int array[], size_t size, int increment) {
    while (size-- > 0) {
        *array++ += increment;
    }
}

Or more readable: use an index variable:

void arrayIncrement(int array[], size_t size, int increment) {
    for (size_t i = 0; i < size; i++) {
        array[i] += increment;
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.