简体   繁体   中英

Passing pointer to memory-mapped interface

I have a global pointer to a memory mapped device initialised as follows:

volatile char *base_address = (char *) 0xa0000000;

During program execution I have a switch statement, and depending on the input the base_address pointer has to be adjusted as you can see below:

    switch (input) {
        case 'S': 
        base_address = (char *) 0xa0001000;
        InitDevice();
    break;
        case 'A': 
        base_address = (char *) 0xa0001000;
        InitDevice();
            break

TBH, this looks like a dirty hack to me and it would be probably nicer to pass the base_address to the function InitDevice((char *) 0xa0001000) . Would the latter be the proper way to do that or are there better approaches?

Many thanks, Alex

Yep, explicitly passing a required parameter to a function is always better than passing it via a global variable.

In an embedded environment, you might have to consider that calling a function with a parameter might require the parameter to be pushed onto the stack and popped otherwise (unless the compiler optimizes and passes it in a register). But I wouldn't optimize based on this unless I have established (through measuring) that the speed gain is actually worth polluting the code.
(And since your example is switching over input, which is usually coming at glacial speed compared to stack operations, this shouldn't be a problem here anyway.)

However, as Lars said in a comment, it would probably be better if those literal addresses were replaced by symbolic constants:

volatile char* const A_base_address = (char *) 0xa0001000;
volatile char* const S_base_address = (char *) 0xa0001000;

switch (input) {
case 'S': 
    InitDevice(S_base_address);
    break;
case 'A': 
    InitDevice(A_base_address);
    break;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM