1

I'm trying to avoid the temporary variable. But I cant figure out the correct syntax:

typedef struct {
  int n;
  int *ptr;
} i_cant_change_this_typedef;

i_cant_change_this_typedef foo;
i_cant_change_this_typedef bar;


int main(void) {
  foo.n = 123;
  int tmp[] = {0x01,0x02,0x03};
  foo.ptr = tmp;

  bar.n = 321;

/* can this be done somehow? */
/*  bar.ptr = {0x03,0x02,0x01};*/
}

It bugs me to have to make the intermediate tmp variable. The commented line at the bottom should show what I'm trying to do.

Can it be done, and how?

Ah yes, I'm using a regular gcc/g++ here.

UPDATE: I see I should have mentioned that I would prefer a solution that worked equally well in C and C++. It's going to be used in an embedded solution where too complex dynamic allocations should be avoided.

5
  • 2
    Please only tag the langauge you are using. C and C++ may have different solutions. Commented Apr 23, 2020 at 16:31
  • 3
    Choose a language. The compound literal works for C but may not work as well for C++. Worth noting that it's also a gcc extension and not necessarily idiomatic if that matters. gcc.gnu.org/onlinedocs/gcc/Compound-Literals.html Commented Apr 23, 2020 at 16:33
  • @sweenish It is an official part of the C standard as of C99. It is stated in the first paragraph of the gcc doc you linked. Commented Apr 23, 2020 at 16:36
  • Point taken, I got hung up on the extension part (for earlier standards), and the C++ aspects. Commented Apr 23, 2020 at 16:37
  • 1
    "I'm trying to avoid the temporary variable" - don't worry about it. Your compilers optimizer will get rid of it in optimized builds. Commented Apr 23, 2020 at 16:44

1 Answer 1

5

You can create a compound literal and have the pointer point to that:

bar.ptr = (int []){0x03,0x02,0x01};
Sign up to request clarification or add additional context in comments.

2 Comments

Ah, nice and simple. Somehow typecasts scare me a little, think I have too many times been down in a hole where I hindered the compiler helping me out.
@mogul: The (int []) in this is not a cast. The source text (int []){0x03,0x02,0x01} is one thing, a compound literal. The type in parentheses has the same syntax as a cast but is not a cast.

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.