1. ## Adding a constant to multiple variables

Hi,

I was hoping someone could help me with this problem.

Code:
```x=x+k
y=y+k
z=z+k```
Is there a more elegant method of adding the same constant to many variables?

Something like:
Code:
`(x, y, z) = (x, y, z) + k  ??`
I tried searching for a solution but couldn't find what I was looking for.

Thanks for any help 2. This C code
Code:
```x=x+k;
y=y+k;
z=z+k;```
Code:
```x+=k;
y+=k;
z+=k;```
Tim S. 3. Thanks Tim, would that be considered the most elegant? 4. There is no "short cut" that I'm aware of to accomplish this. The best case scenario would be if those "many variables" were elements in an array - in which case you could just use a loop.

You could also write your own elegant solution - therein lies the beauty of 'C'. 5. Originally Posted by melia789 Thanks Tim, would that be considered the most elegant?
Depending on the problem, writing a function could be the most elegant solution.

If you have to do it three or more times; I say write a function.
Once only, not really worth a function.
Twice, it is had to decide what is better.

Tim S. 6. You could define x,y,z in a structure and make a function which adds the values

Code:
```#include <stdio.h>
#include <stdlib.h>

struct point_t
{
int x;
int y;
int z;
};

/* Add 'k' to x, y, z */
void add_k(struct point_t *p, int k);

int main(int argc, char *argv[])
{
struct point_t point;

int k = 4;

point.x = 1;
point.y = 1;
point.z = 1;

printf("First Values:\tx=%d\ty=%d\tz=%d\n", point.x, point.y, point.z);

printf("Results:\tx=%d\ty=%d\tz=%d\n", point.x, point.y, point.z);

return EXIT_SUCCESS;
}

void add_k(struct point_t *p, int k)
{
p->x += k;
p->y += k;
p->z += k;
}``` Popular pages Recent additions add, constant, multiple, variables 