Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

Option parsing.

Name: Anonymous 2008-05-18 21:18

I just wrote two versions of a simple option parsing function with that supports, specifically, --long options with parameters.

Which one do you prefer? (I am not asking you about style, and don't tell me to use existing [sub]and bloated[sub] libraries.)

The first one stores long options in a "previous" variable:


#include <stdio.h>

int main(int argc, char *argv[]) {
    int i;
    char *previous = NULL;

    for (i = 1; i < argc; i++) {
        if (!previous && !strncmp(argv[i], "--", 2)) {
            /*if option starts with --*/
            previous = argv[i];
            continue;  /*skip assignment of previous*/
        } else if (previous && !strcmp(previous, "--long")) {
            /*if previous option was --long*/
            printf("ZOMG %s is LOOONG\n", argv[i]);
        } else if (previous) {
            goto lostthegame;
        } else {
            printf("%s\n", argv[i]);
        }
        previous = NULL; /*NULL NULL NULL NULL NULL*/
    }

    if (!previous) return 0;

    lostthegame:
    printf("Unrecognized option, sorry, you lost the game\n");
    return 1;
}


The second one increments i to access the next array element directly:


#include <stdio.h>

int main(int argc, char *argv[]) {
    int i;

    for (i = 1; i < argc; i++) {
        if (!strncmp(argv[i], "--", 2)) {
            /*if option starts with --*/
            if (++i == argc)
                /*and is not the last arg*/
                goto lostthegame;
           
            if (!strcmp(argv[i - 1], "--long"))
                printf("ZOMG %s is LOOONG\n", argv[i]);
            else
                goto lostthegame;
           
        } else {
            printf("%s\n", argv[i]);
        }
    }
    return 0;

    /*this makes less sense in this version*/
    lostthegame:
    printf("Unrecognized option, sorry, you lost the game\n");
    return 1;
}


Both are just simple ideas I got. I'm just asking you, EXPERT PROGRAMMERS how ``hackish'' do you think it is

Name: Anonymous 2008-05-18 21:45

null is not necessarily false

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List