Home > Blockchain >  Global or local when creating a function
Global or local when creating a function

Time:07-27

Hey I'm trying to write a basic assembler it doesn't even do real machine language, the premise is to learn how to code in c ansi 90.

I have made a function that gets a string that supposedly has an instruction from a set of 16(mov, cmp, jmp,...), and I need to compare the string to know if its truly a one of the instructions.

I made a local two-dimensional array of char in the function with all the 16 instructions, and I use this array to compare to the string and send back a number depicting the instruction if found equal.

this function will be used almost all the time, and the assembler needs to be fast if for instance it needs to assemble a source code with millions of instructions.

should I change the array from local to global will it change anything?

Thanks.

Edit: the code.

command_type is_command(char * string)
{
    int i;
    command_type type = NAN;
    char * command_names[] = {"mov", "cmp", "add", "sub", "not",
                              "clr", "lea", "inc", "dec", "jmp",
                              "bne", "get", "prn", "jsr", "rts",
                              "hlt"};
    
    for(i = 0; i < 16; i  )
    {
        if(!strcmp(string, command_names[i]))
        {
            type = i   1;
        }
    }
    
    return type;
}

CodePudding user response:

Since the contents of the strings will not change, declare the element type const. Since the addresses of the strings will not change, declare the pointer type const.

Since the array is needed throughout the entire execution of the program, declare it static.

static const char * const command_names[] = {
        "mov", "cmp", "add", "sub", "not",
        "clr", "lea", "inc", "dec", "jmp",
        "bne", "get", "prn", "jsr", "rts",
        "hlt"
    };

In general, the more information you give the compiler about something, the better a job it can do.

  • Related