开发者

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开发者_C百科 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;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜