Skip to content

Argument parsing simplification #9

Description

@kloetzl

Hi,

I noticed that your argument parsing is unnecessarily complex. Here are two ideas to make it simpler. First, you have a lot of repetitive code, just checking for simple flags. Using a vector a lot of that can be folded away.

int main(int argc, char **argv){
	auto simple_flags = std::vector<std::pair<std::string,bool&>>({
		{"-a_cob", APPROX_CUT_ONE_B},
		{"-a_c2b", APPROX_CUT_TWO_B},
		{"-a_c2br", APPROX_CUT_TWO_B_ROOT} // ToDo: list all other flags
	});

	int max_args = argc-1;
	while (argc > 1) {
		char *arg = argv[--argc];
		auto it = std::find_if(simple_flags.begin(), simple_flags.end(), [=](const std::pair<std::string,bool&>& flag){
			return flag.first == arg;
		});
		if (it != simple_flags.end()) {
			it->second = true;
			continue;
		}

		// deal with more complicated flags …
	}

	// rest of main …
}

Second, for -pairwise you use a lot of nested ifs. Inverting the logic here can help.

else if (strcmp(arg, "-pairwise") == 0)
{
	PAIRWISE = true;
	QUIET = true;

	do {
		if (max_args <= argc)break;
		if (argv[argc + 1][0] == '-') break;

		PAIRWISE_START = atoi(argv[argc + 1]);

		if (max_args <= argc + 1)break;
		if (argv[argc + 2][0] == '-') break;

		PAIRWISE_END = atoi(argv[argc + 2]);

		if (max_args <= argc + 2)break;
		if (argv[argc + 3][0] == '-') break;

		PAIRWISE_COL_START = atoi(argv[argc + 3]);

		if (max_args <= argc + 3)break;
		if (argv[argc + 4][0] == '-') break;

		PAIRWISE_COL_END = atoi(argv[argc + 4]);
	} while (0);
}

Best,
Fabian

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions