简体   繁体   English

从内部if语句(C)声明全局变量

[英]Declare global variable from inside if statement (C)

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. 我试图从if语句中声明一个变量,因为基于条件,该变量将具有不同的类型以供以后使用。

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. 其中Odd_int_type和Even_int_type都是具有IFG成员的结构。 getType just returns 1 if odd and 0 if even. 如果奇数,getType仅返回1,如果偶数则返回0。

However, the scope of _port is within the if statement so it doesn't work. 但是,_port的范围在if语句内,因此它不起作用。 Is there a workaround? 有解决方法吗?

Trying to do this for a project I'm working on with the MSP432P401R microcontroller. 尝试针对我正在使用MSP432P401R微控制器的项目执行此操作。

When you declare a variable inside the if scope, it won't be accesible outside it due to the scope limitation. 当您在if范围内声明变量时,由于范围限制,在变量之外将无法访问该变量。 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. 假设您只想根据奇/偶端口指向不同的数据,则只需要将_port的范围扩大到所需的范围即可。 If you are trying to access same memory with different variables, one way you can do it is using a union of structs. 如果您尝试使用不同的变量访问相同的内存,则可以使用结构的union来实现。 You will need to increase the scope of the variable anyway. 无论如何,您将需要增加变量的范围。

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. 您可以在函数,文件或全局范围内声明_port变量,然后在gpio_flag函数中设置其值。 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; 如果DIO_PORT_Odd_Interruptable_TypeDIO_PORT_Even_Interruptable_TypeDIO_PORT_Even_Interruptable_Type的别名,则只需定义PORT_t _port; and track whether it is odd or even with bool _portIsEven; 并使用bool _portIsEven;跟踪它是奇数还是偶数bool _portIsEven; .

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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