如何识别静态变量的范围?

How to identify scope of static variable?

我正在尝试了解基本的引导加载程序。这是一个在 while 循环中调用的函数:

static void uart_task(void)
{
  static int ptr = 0;
  static int command = 0;
  static int size = 0;
  uint8_t *byte_buf = (uint8_t *)uart_buffer;
  int data;

  if (uart_command)
    return;

  if (0 == UART_SERCOM->USART.INTFLAG.bit.RXC)
    return;

  data = UART_SERCOM->USART.DATA.reg;

  if (timer_expired())
    command = 0;

  if (0 == command)
  {
    ptr = 0;
    command = data;
    uart_buffer[0] = 0;

    if (BL_CMD_UNLOCK == command)
      size = CMD_UNLOCK_SIZE;
    else if (BL_CMD_DATA == command)
      size = CMD_DATA_SIZE;
    else if (BL_CMD_VERIFY == command)
      size = CMD_VERIFY_SIZE;
    else if (BL_CMD_RESET == command)
      size = CMD_RESET_SIZE;
    else
      size = 0;
  }
  else if (ptr < size)
  {
    byte_buf[ptr++] = data;
  }

  if (ptr == size)
  {
    uart_command = command;
    command = 0;
  }

  timer_reset();
}

static int command = 0 在函数的顶部初始化。

向下 16 行 command 的值已检查; if (0 == command)

if 语句不会总是 return 正确吗? command 的值如何在其声明和被检查的值之间更改?

static 变量在函数调用之间保持它们的值。此外,它们不会在函数开始时进行初始化;他们从项目开始就具有自己的价值。

例如,使用静态变量,

int foo(int bar)
{
    static int baz = 0;

    if(bar)
        baz = 1;

    return baz;
}

不一样
int foo(int bar)
{
    static int baz;

    baz = 0;

    if(bar)
        baz = 1;

    return baz;
}

在第一个示例中,当使用非零参数调用 foo 时,它将 return 1 来自该调用和任何后续调用。在第二个中,当传递一个非零参数时,foo 仅 returns 1,否则总是 returns 0

在您的情况下,command 就在这里更改:

  if (0 == command)
  {
    ptr = 0;
    command = data; // here
    uart_buffer[0] = 0;

并且,除非 ptr == size 或计时器已过期,否则它将为下一次调用保留该值。