Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C variable declared and assigned to function call

Tags:

c

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; }   
}
like image 542
Pi Squared Avatar asked Dec 06 '25 08:12

Pi Squared


1 Answers

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);
}
like image 55
VillageTech Avatar answered Dec 08 '25 20:12

VillageTech