Home > Blockchain >  Is there any alternative to using if walls instead of something else in C ?
Is there any alternative to using if walls instead of something else in C ?

Time:10-22

I'm doing some C and my app accepts subcommands, for example ./my_app test 123.

I'm semi-new to C and I can't find anything on the internet so I don't know haha.

For example in python I'd do:

#!/usr/bin/env python3

import sys

def test(num):
    print(f"Test {num}")

subcommands = {"test": test}

subcommands[sys.argv[1](sys.argv[2])

any C eq to this? if so, should I use it or stick to if-else_if-else?

CodePudding user response:

Have a look at std::map/std::unordered_map, for example:

#include <iostream>
#include <map>
#include <string>

void test(const std::string &value) {
    std::cout << "Test " << value << std::endl;
}

using cmdFuncType = void(*)(const std::string &);

const std::map<std::string, cmdFuncType> subcommands = {
    {"test": &test}
};

int main(int argc, char* argv[]) {
    if (argc != 3) {
        std::cerr << "usage: program command value" << std::endl;
        return 0;
    }

    auto iter = subcommands.find(argv[1]);
    if (iter == subcommands.end()) {
        std::cerr << "unknown command: " << argv[1] << std::endl;
        return 0;
    }

    iter->second(argv[2]);
    return 0;
}

CodePudding user response:

Is this what you are trying to achieve:

#include <string>
#include <functional>
#include <iostream>
#include <map>

void test(int num) {
    std::cout << "Test " << num << "\n";
}

std::map<std::string, std::function<void(int)>> subcommands = {
    {"test", test}
};

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

    subcommands[argv[1]](std::atoi(argv[2]));
}
  • Related