Home > Mobile >  C language : How to store data of structure in one line?
C language : How to store data of structure in one line?

Time:08-28

I have a structure that stores coordinates (xi,yi).

typedef struct _FCOORD{
    float X;
    float Y;
}FCOORD,*PFCOORD;

Now I define a variable named point and store some data

FCOORD point;
point.X=20.00f;
point.Y=20.00f;

I want to just load data like this:

point={20.00f,20.00f};

I am coding in C language using gcc compiler

C:\My_Assets\MinGW\bin>gcc --version
gcc (x86_64-posix-seh-rev0, Built by MinGW-W64 project) 7.3.0
Copyright (C) 2017 Free Software Foundation, Inc.

I get this error when compiling

gcc -c ./src/main.c -I"F:\Codes\Windows\Application\include"
In file included from ./src/main.c:13:0:
./src/threads.c: In function 'WorkerThread':
./src/threads.c:66:19: error: expected expression before '{' token
     R1_data.start={10,10};
                   ^

EDIT: Please mention similar case for structure pointer too i.e PFCOORD. Thank you.

CodePudding user response:

You can use a compound literal for such an assignment:

#include <stdio.h>

typedef struct FCOORD {
    float X;
    float Y;
} FCOORD;

int main()
{
    FCOORD point;
    point.X = 20.00f;
    point.Y = 20.00f;

    point = (FCOORD){ 42.00f, 3.1415927f }; // The RHS here is a compound literal

    printf("%f %f\n", point.X, point.Y);
    return 0;
}

Note that, as mentioned on the linked cppreference page, although they look a lot like casts, compound literals are not casts and behave very differently.

Also note that I removed the leading underscore from your _FCOORD type name; identifiers with leading underscores followed by an uppercase letter are reserved for use by the implementation.

You can also add designated initializers to the assignment shown in the code above; this may be useful if you want to assign the elements "out of order", or if there are other structure members that you don't want to explicitly assign1. Using these, the line would be like this:

    point = (FCOORD){ .Y = 3.1415927f, .X = 42.00f };

1 But, be careful in the latter case (where you have members that are not explicitly set in the compound literal): These will not keep their 'original' values but will, instead, be default initialized.

CodePudding user response:

You can do this when declaring and initializing at the same time.

typedef struct A { int b; int c; } At;

int main(void) {
  At a = {.b=42, .c=27};

  return 0;
}

But you cannot use this after declaration. This will not compile.

typedef struct A { int b; int c; } At;

int main(void) {
  At a;
  a = {.b=42, .c=27};

  return 0;
}

Outside of initialization, you can assign a compound literal. Note that this is a C99 feature, and you may have problems with this if using an older compiler. If so, get a new compiler.

typedef struct A { int b; int c; } At;

int main(void) {
  At a;
  a = (At){.b=42, .c=27};

  return 0;
}
  • Related