0
enum cmd {hello, hi, bye};

int main(int argc, char *argv[]) {
    if(argc < 2)
        usage(usg);

    enum cmd command = argv[1];
    if(command == 0) {
        ...
    }
}

I get this error incompatible types when initializing type ‘enum cmd’ using type ‘char * is there different way using enum?

woowoo
  • 117
  • 1
  • 6

1 Answers1

3

You can't assign a string to a variable with type enum. Enum in C is a type that consists of integral constants. You either need to work with the pre processor or create a custom function that will set the enum cmd the correct value by comparing argv. This works:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAX_CMDS 3

typedef enum { hello , hi , bye}cmd;

cmd decide_command(char *arg)
{
    char *commands[] = { "hello", "hi" ,"bye" };

    for (int i = 0; i < MAX_CMDS; i++)
    {
        if (!strcmp(commands[i],arg)) /* comparing each of the commands with argv[1] */
        {
            return i; /* since hello == 0 in enum cmd, the correct value will set, if found */
        }
    }

    fprintf(stderr,"Unknown command %s",arg);

    exit(EXIT_FAILURE);
}

int main(int argc,char **argv)
{
    cmd command = 0;

    if (argc < 2)
    {
        /* error handling */
    }

    command = decide_command(argv[1]);

    /* code */

    exit(EXIT_SUCCESS);
}
alex01011
  • 1,670
  • 2
  • 5
  • 17