Reputation: 31
I am trying to declare a variable from inside an if statement because based upon a condition, the variable will be of a different type to be used later.
uint8_t gpio_flag(PORT_t * port, uint8_t pin) {
if(getType(port)) { // odd
DIO_PORT_Odd_Interruptable_Type * _port = port;
}
else { // even
DIO_PORT_Even_Interruptable_Type * _port = port-1;
}
return ((_port->IFG & (1<<pin))==1);
}
Where the Odd_int_type and Even_int_type are both structs that have an IFG member. getType just returns 1 if odd and 0 if even.
However, the scope of _port is within the if statement so it doesn't work. Is there a workaround?
Trying to do this for a project I'm working on with the MSP432P401R microcontroller.
Upvotes: 0
Views: 2798
Reputation: 31
When you declare a variable inside the if scope, it won't be accesible outside it due to the scope limitation.
Assuming you just want to point to different data depending on odd/even port, you just need to increase the scope of _port to whatever you need.
If you are trying to access same memory with different variables, one way you can do it is using a union
of structs. You will need to increase the scope of the variable anyway.
Upvotes: 1
Reputation: 6659
You cannot declare anything outside the current scope that isn't extern. You can declare _port variable in function, file or global scope, then set its value in your gpio_flag
function. If DIO_PORT_Odd_Interruptable_Type
and DIO_PORT_Even_Interruptable_Type
are aliases for PORT_t, then you can simply define PORT_t _port;
and track whether it is odd or even with bool _portIsEven;
.
Upvotes: 0