繁体   English   中英

在 C 中,当需要将 arguments 的函数或逻辑条件拆分为多行时,是否需要反斜杠字符(\)?

[英]In C, is the backslash character (\) required when one needs to split arguments of functions or logical conditions into multiple lines?

我最近看到了这段代码:

static HAL_StatusTypeDef Program_Flash_Page(uint32_t const page_address, \
  void* const pBufferData, uint32_t const nBufferSize) {

  uint32_t Address = page_address;
  uint64_t *DATA_64 = (uint64_t *) pBufferData;
  while (Address < (page_address + nBufferSize)) {

    if (HAL_FLASH_Program(FLASH_TYPEPROGRAM_DOUBLEWORD, Address, *DATA_64) == \
      HAL_OK) {
      Address = Address + 8;
      DATA_64++;
    }
    else {
      return HAL_ERROR;
    }

  }

  return HAL_OK;

}

如您所见,反斜杠用于表示 arguments 列表和多行逻辑条件。

正如我从 Kernighan 和 Ritchie(第 2 版,第 A.12.2 段,第 207 页)中了解到的那样,在预处理过程中,“以反斜杠 \ 字符结尾的行通过删除反斜杠和以下换行符来折叠”。

我仍然不清楚的是,如果这种语法是强制性的,或者在编码时是否可以只使用换行符(按回车键)。

斜杠是可选的,除了 Gerhardh 提到的定义多行宏。

#include <stdio.h>

//valid macro
#define BAR(x, y, z) printf("%d %c %f\n", \
                            x, \
                            y, \
                            z);

//invalid macro, this won't compile if uncommented
/*
#define BAR(x, y, z) printf("%d %c %f\n",
x,
    y,
    z);
*/

void foo(int x, char y, float z) {
    printf("%d %c %f\n", x, y, z);
}

int main() {
    //valid
    foo(5, \
        'c', \
        0.0f);

    //also valid
    foo(5,
        'c',
        0.0f);

    //even use of the macro without slashes is valid
    BAR(5,
        'c',
        0.0f);

    return 0;
}

暂无
暂无

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

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