Home > Mobile >  C99 shorthand for operations on fields of a single struct variable?
C99 shorthand for operations on fields of a single struct variable?

Time:05-19

Let's say I have this simple program:

#include <stdio.h>

typedef struct foo {
  int bar;
  int baz;
  double qux;
} foo_t;

foo_t my_foo = {
  .bar = 0,
  .baz = 0,
  .qux = 0,
};

int main() {
  my_foo.bar = 100;
  my_foo.baz = my_foo.bar/2   4;
  my_foo.qux = my_foo.bar/3.0   my_foo.baz/5.0;
  printf("Hello, world %f!", my_foo.qux);
  return 0;
}

Above, I'm using the "designated initializer style" { .bar = 0, ...} to initilize the struct variable, which I consider a kind of a shorthand.

I was wondering - is there some shorthand syntax, that would also allow for operations on fields of the same struct variable? For instance, instead of writing:

  my_foo.bar = 100;
  my_foo.baz = my_foo.bar/2   4;
  my_foo.qux = my_foo.bar/3.0   my_foo.baz/5.0;

... I could imagine a shorthand syntax like this (below pseudocode somewhat inspired by Python):

with(my_foo) {
  .bar = 100;
  .baz = .bar/2   4;
  .qux = .bar/3.0   .baz/5.0;
}

Is there something like this in C (C99, to be more specific)?

CodePudding user response:

C has no such syntax. You need to specify the struct variable followed by the member name.

The closest you can come to this is to create pointers to each member and work with those.

int *bar = &foo.bar;
int *baz = &foo.baz;
double *qux = &foo.qux;
*bar = 100;
*baz = *bar/2   4;
*qux = *bar/3.0   *baz/5.0;

CodePudding user response:

Use the KISS principle. Meaning stick to simple, existing features in order to create readable, maintainable code:

void fooify (foo_t* dst, const foo_t* src)
{
  int bar = src->bar;    
  int baz = src->baz;
  double qux = src->qux;

  bar  = 100;
  baz = bar/2   4;
  qux = bar/3.0   baz/5.0;

  *dst = (foo_t) 
  {
    .bar = bar,
    .baz = baz,
    .qux = qux,
  };
}
  • Related