0

I'd like to set a group of 2-4 variables, their values dependent on a 5th variable. I can do it by a long list of if else, I was wondering if there was a trick I don't know about I could learn, to do it a little more elegantly? I'm still very new to ``C.

For example:

/*some code... x is read from stdin...*/

if (x == 1) {
  a = 10;
  b = 100;
}

else if (x == 2) {
  a = 10;
  b = 50;
  c = 100;
}

else if (x == 3) {
  a = 0;
  b = 25;
  c = 50;
  d = 100;
}
/* and so on...*/

I'm planning to do it all in a function away from main() using pointers to set a,b,c... but I've omitted it here for simplicity.

Cheers,

W

4
  • If the variables a, b, c, d... are logically related, you might want to consider putting them in a struct.
    – Samantha
    May 11, 2018 at 8:43
  • A trick? You don't need a trick! You need a feature called switch().
    – machine_1
    May 11, 2018 at 8:52
  • Lots of really useful stuff, thanks everyone! I upvoted the ones that I understand :D I think a switch or a 2D array will be the way forward at my level. Will choose a Best Answer later.
    – Weaver
    May 11, 2018 at 10:45
  • what do you do of d if it isn't affected ? Can you include a better minimal reproducible example, with this we could advise you much better.
    – Stargateur
    May 11, 2018 at 15:55

9 Answers 9

3

Well, a switch statement is generally more elegant than a bunch of if-elsestatements

switch (x) {
    case 1:    a = 10;
               b = 100;
               break;

    case 2:    a = 10;
               b = 50;
               c = 100;
               break;

    case 3:    a = 0;
               b = 25;
               c = 50;
               d = 100;
               break;

    default:   // have a default case or catch it as an error
}

And you could tighten the code a little more by using functions to set the variables, if you really care about keeping this section of code short and easy to read.

switch (x) {
    case 1:    caseA(&a, &b);
               break;

    case 2:    caseB(&a, &b, &c);
               break;

    case 3:    caseC(&a, &b, &c, &d);
               break;

    default:   // have a default case or catch it as an error
}

void caseA(int *a, int *b) {
    *a = 10;
    *b = 100;
}
2

You can use switch(x) which will allow you to recycle some code if a few values have identical effects. For instance

switch(x){
    case 5:
    case 6:
        a=0;
        b=25; //this code will run for both cases
}

with limitations of course. You can't really apply this to every case.

Also by using ternary operators you can handle some borderline cases. Imagine for example a=10 every time except when x==2, then it is 5 . Therefore you can handle that single variable like this: a = (x==2)?5:10;

2

My way, for what it's worth which tractably separates the data from the program functionality:

int data[3][4] = {  
   {10, 100, 0, 0},
   {10, 50, 100, 0},
   {0, 25, 50, 100}
};

a, b, c, and d become a particular row of this array, which you index with

data[-1 + x]
1
  • Thanks for this. I didn't use it in this particular problem, but played with it and like how it works. Now I have it in mind can see it'll be useful in something else I'm planning to do. Shame I can't pick 2 best answers :)
    – Weaver
    May 15, 2018 at 7:58
2
static const int a[4] = {10, 10, 0};
static const int b[4] = {100, 50, 25};
static const int c[4] = {0, 100, 50};
static const int d[4] = {0, 0, 100};

printf("%d %d %d %d\n", a[x - 1], b[x - 1], c[x - 1], d[x - 1]);

or using Mathematics, and with specific values in mind:

// if (x == 1){a = 10; b = 100;}
// else if (x == 2){a = 10; b = 50; c = 100;}
// else if (x == 3){a = 0; b = 25; c = 50; d = 100;}

void get_values(int x, int *a, int *b, int *c, int *d)
{
   *a = (1 - x / 3) * 10;
   *b = 100 >> (x - 1);
   *c = (x - 1) * (200 >> (x - 1));
   *d = (x / 3) * 10;
}

int main(void)
{
    int a, b, c, d;
    int x = 3;

    get_values(x, &a, &b, &c, &d);
    printf("%d %d %d %d\n", a, b, c, d);
    return (0);
}

will usually be faster than all above solutions as compilers are not able to make these ultra specific optimizations but it depends on your needs. Also the last one, while being the fastest, will definitely hurt readability so you should keep computed values as comment.

1

If the x values are actually sequential, then you can create an array of structs to hold the values for a,b,c,d. The only trick is that you need a sentinel value to indicate that a variable should not be set. In the example below, a value of -1 is the sentinel value.

struct setting
{
    int a, b, c, d;
}
settings[] =
{
    {  0,   0,  0,    0 },     // x = 0 not used
    { 10, 100, -1,   -1 },     // -1 indicates that a variable should be skipped
    { 10,  50, 100,  -1 },
    {  0,  25,  50, 100 },
};
static int maxSetting = sizeof(settings) / sizeof(settings[0]);

void updateSettings(int x, int *a, int *b, int *c, int *d)
{
    if (x > 0 && x < maxSetting)
    {
        struct setting *sptr = &settings[x];
        if (sptr->a >= 0)
            *a = sptr->a;
        if (sptr->b >= 0)
            *b = sptr->b;
        if (sptr->c >= 0)
            *c = sptr->c;
        if (sptr->d >= 0)
            *d = sptr->d;
    }
}
0

If you feel like hacking you could do this fancy trick:

typedef enum
{
    CASE_1_ = 1,
    CASE_2_,
    CASE_3_

}states;

void caseA(int *a, int *b, int *c, int *d) {
    *a = 10;
    *b = 100;
}

typedef void (*fp)(int *, int *, int *, int *);

fp proccess[] = {[CASE_1_] = caseA, [CASE_3_] = caseB, [CASE_3_] = caseC};

All you need to do is proccess[x]();, and you won't need any switch or if-else statements.

0

Just for fun, if you want to complicate things for now, but make your life easier going ahead with multiple such scenarios, I have a solution which at first looks very ugly to implement, but I love the way it works in terms of scalability and re-usability.

The code below works in an interactive way for testing purposes, discard whatever you feel unnecessary.

#include<stdio.h>                                                                     

// Lets get handlers for each value                              
int f_One(void);
int f_Two(void);
int f_Three(void);
int f_Four(void);

// Lets have them in an enum rather than mere numbers, may not be required for you
typedef enum {

    ONE = 1,
    TWO,
    THREE,
    FOUR,

    MAX_TASKS,
    TASK_INVALID = -1,

} eValue_t ;

// This is a structure that binds an input and a handler together
typedef struct stTask {

    eValue_t TaskID;
    int (*handler) (void);

} stTask_t;

// Lets have an object
stTask_t Task;

// This is a like look-up table for referencing inputs and their handlers
const stTask_t TaskList[MAX_TASKS-1] =
{
    { ONE,    f_One   },
    { TWO,    f_Two   },
    { THREE,  f_Three },
    { FOUR,   f_Four  },
}; 

// This is your data
int a, b, c, d;

// Handler for 1
int f_One(void)
{
    printf("\nOne: ");
    a = 10;
    b = 100;
    printf("a is %d, b is %d", a, b);

    return 1;
}

// Handler for 2
int f_Two(void)
{
    printf("\nTwo: ");
    a = 10;
    b = 50;
    c = 100;
    printf("a is %d, b is %d, c is %d", a, b, c);

    return 2;
}

// Handler for 3
int f_Three(void)
{
    printf("\nThree: ");
    a = 0;
    b = 25;
    c = 50;
    d = 100;
    printf("a is %d, b is %d, c is %d, d is %d", a, b, c, d);

    return 3;
}

// Handler for 4
int f_Four(void)
{
    printf("\nFour: I didn't set any :D");
    return 4;
}

int main (void)
{
    int Val = -1;
    int ret = 0;

    while(1)
    {
        // Get input
        printf("\n\nPress 1, 2, 3, 4 or 0 for exit, Enter a value: ");
        scanf("%d", &Val);
        // Some validation, can be improved, or discarded
        if(Val > 4)
        {      
            printf("\nInvalid input");
            continue;
        }
        else if(Val == 0)
        {
            printf("\nExiting...");
            break;
        }
        // Assign the task
        Task.TaskID = Val-1;
        // Load the handler
        Task.handler = TaskList[Task.TaskID].handler;
        // Execute the handler
        ret = Task.handler();
        // Do something with 'ret'
    }
    printf("\n\n");
    return 0;
}
0

Yo can use union with enumeration. Size of the structure always be the one of the biggest content structure tho.

enum type
{
    BAR = 0,
    BAZ,
    OTHER,
};

struct bar
{
    int x;
    char y;
};

struct baz
{
    void * x;
    float y;
};

struct other
{
    char x[2];
};

typedef struct _foo
{
    enum type type;
    union
    {
        struct bar bar;
        struct baz baz;
        struct other other;
    };
} foo;

...

struct bar a = { 1, 'c', };

foo x;
x.type = BAR;
x.bar = a;


struct baz b = { NULL, 1.0f, };

foo y;
y.type = BAZ;
y.baz = b;

if (x.type == BAR)
    printf("%d\n", x.bar.x);

if (y.type == BAZ)
    printf("%p\n", y.baz.x);
-1

Just for the sheer fun of it, you can use variadic functions. Here is how one might do that (with usage example, you can easily put it into your if ladder):

#include <stdarg.h>
#include <stdio.h>

void set_bunch(int n_vars, ...) {
    va_list args;
    va_start(args, n_vars);
    for (int i = 0; i < n_vars; ++i) {
        int* varp = va_arg(args, int*);
        int varv = va_arg(args, int);
        *varp = varv;

    }
    va_end(args);
}

int main() {
    int a, b, c, d;

    set_bunch(2, &a, 20, &b, 30);
    printf("%d %d\n", a, b); // prints 20 30

    set_bunch(3, &a, 30, &b, 40, &c, 50);
    printf("%d %d %d\n", a, b, c); // prints 30 40 50
}

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.