[csw-maintainers] initialization problem: struct + union

James Lee james at opencsw.org
Sun Jun 5 10:24:13 CEST 2011


On 03/06/11, 22:53:46, Philip Brown <phil at bolthole.com> wrote regarding
[csw-maintainers] initialization problem: struct + union:

> A chopped down version, which compiles with gcc, but fails under sun cc:
> ( complains about the    {integer:2}  thing at bottom)


> #include <stdio.h>
> union types {
>   char *string;
>   int integer;
> };
> typedef struct {
>   char *option;
>   int type;
>   union types default_value;
> } config_opt_t;

> #define INTEGER 1

> config_opt_t config_opts[] = {
>   { "snmp_timeout", INTEGER, {integer:2} },
> };


Remove the type qualifier and it compiles with just a warning.

config_opt_t config_opts[] = {
  { "snmp_timeout", INTEGER, 2 },
};


Simple case warning avoidance, declare integer first:

union types {
   int integer;
   char *string;
};




Extending the code to use both types in the union this complies with
warning and runs:



$ cat test.c
#include <stdio.h>
union types {
  char *string;
  int integer;
};
typedef struct {
  char *option;
  int type;
  union types default_value;
} config_opt_t;

#define INTEGER 1
#define STRING 2

config_opt_t config_opts[] = {
  { "snmp_timeout", INTEGER, 2 },
  { "snmp_message", STRING, "time out exceeded" },
};


int main(int argc, char* argv[])
{
    int i;
    for (i = 0; i < sizeof(config_opts) / sizeof(config_opt_t); i++) {
        switch (config_opts[i].type) {
            case INTEGER:
                printf("%s: %d\n", config_opts[i].option,
                                   config_opts[i].default_value.integer);
                break;
            case STRING:
                printf("%s: %s\n", config_opts[i].option,
                                   config_opts[i].default_value.string);
                break;
        }
    }
    return 0;
}
$ cc test.c
"test.c", line 16: warning: improper pointer/integer combination: op "="
$ ./a.out
snmp_timeout: 2
snmp_message: time out exceeded





James.


More information about the maintainers mailing list