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;
}
}
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;
}
}
sizeis 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 passsize - 1then it's a very unconventional APIwhile(size--) array[size] +=increment;