Pi Squared
Pi Squared

Reputation: 31

C variable declared and assigned to function call

The local variable btmp in the below code is declared with an assignment to a function call. That function is reading the value of a register RegX. The next line writes to another register Reg_ADDR, which is the purpose of these lines of code. The lines thereafter potentially update btmp.

As this function does not return anything, is there any purpose to the last 4 lines of code? Or is there something complicated going on, e.g. btmp is some sort of pointer?

void SetDeviceAddress( uint8_t address, ENUM_MODE AddressMode)
{   
    uint8_t btmp = DeviceReadReg( RegX ) & ~0x03;
    DeviceWriteReg(Reg_ADDR, address);
    if     ( AddressMode == MODE0 )     {}
    else if( AddressMode == MODE1 )     { btmp |= 0x01; }
    else if( AddressMode == MODE2 )     { btmp |= 0x02; }
    else if( AddressMode == MODE3 )     { btmp |= 0x03; }   
}

Upvotes: 3

Views: 80

Answers (1)

VillageTech
VillageTech

Reputation: 2015

The 'btmp' variable is the local variable, so any write/change operations related to this are lost while clearing the stack on function return. Moreover, it seems that the first line of this code is useless too - as long as the DeviceReadReg() call has no side effects (if it has, this is really bad coding practice). So, the real equivalent of the function is:

void SetDeviceAddress(uint8_t address, ENUM_MODE AddressMode)
{   
    DeviceWriteReg(Reg_ADDR, address);
}

or better:

void SetDeviceAddress(uint8_t address)
{   
    DeviceWriteReg(Reg_ADDR, address);
}

Upvotes: 1

Related Questions