0
#define HOST_NAME "UDP"
#define ADDRESS "127.0.0.1" 
struct UDP_IP_Parameters { 
        uint version; /* e.g. "1.0" = 0x0100 */
        uint port; /* PORT */
        taggedunion {
            "HOST_NAME" char[256];
            "ADDRESS" char[15];
        };
};

int main()
{
struct UDP_IP_Parameters udp;
udp.version = 0x0100;
udp.port = 444;

}

I have created a structure and taggedunion nested within that. Is it possible to define the host name and address as constant like above ?? Is it possible to assign some values by creating a objects for it. Could anyone give me some ideas.

user2984410
  • 39
  • 2
  • 7

1 Answers1

3

That is not C.

No, you can't specify values inside a type declaration.

The closest you can do is probably something like:

typedef struct {
  uint16_t version; /* Guessing size requirements. */
  uint16_t port;
  bool resolved;
  union {
    char host_name[256];
    char address[24];
  } addr;
} UDP_IP_Parameters;

The above uses the resolved flag to "tag" the union, so the program can know which member of the union is valid.

You should be able to initialize an instance like so:

UDP_IP_Parameters so = { 0x100, 80, false, { "stackoverflow.com" } };

Not sure if (in C99) you can use the dotted syntax to do this:

UDP_IP_Parameters so = { 0x100, 80, true, { .address = "198.252.206.16" } };
unwind
  • 391,730
  • 64
  • 469
  • 606
  • is it possible to use bool ?? I am getting error as : syntax erro : identifier bool . – user2984410 Nov 28 '13 at 09:05
  • @user2984410 `bool` is a standard type since C99, but you need to `#include `. If you're using a non-C99 compiler (such as Visual Studio), it won't work. – unwind Nov 28 '13 at 09:14
  • I include stdbool.h then also I am getting error like :fatal error C1083: Cannot open include file: 'stdbool.h': No such file or directory – user2984410 Nov 28 '13 at 09:18