是否可以在 C/C++ 中 for 循环的增量部分执行多个操作

Is it possible to do multiple operations in increment part of for loop in C/C++?

本文关键字:量部 执行 操作 循环 for C++ 是否      更新时间:2023-10-16

是否可以在 C/C++ 中以 for 循环的增量部分执行多个操作?像这样:

int a = 0, b = 0, c = 5;
for(; a < c; increase a by 1 and increase b by 2)

使用逗号运算符:

for (; a < c; ++a, b += 2)

是的,这是可能的。您还可以在循环中声明多个变量,并且不需要事先执行此操作。

for (int a = 0, b = 0, c = 5; a < c; ++a, b += 2)

@Zoey Hewll的评论:

声明不同类型的多个变量怎么样?

@AliciaBytes的评论:

for 循环中的多个声明仅在它们都属于同一类型时才有效。

这可能接近异端邪说,但您可以使用struct来包含多个不同类型的变量,如下所示:

#define BENCHMARK(elasped)                                                     
    for (                                                                      
        struct { uint8_t done; uint32_t start; } __metadata =                  
            { 0, systick_get() };                                              
        !__metadata.done;                                                      
        ((elasped) = elasped_time(__metadata.start)), __metadata.done = 1      
    )
<小时 />

编辑:这是一个更完整的示例

#include <stdint.h>
#include <stdio.h>
volatile uint32_t g_systick = 0; //< Incremented by the system clock somewhere else in the code
uint32_t systick_get(void)
{
    return g_systick;
}
uint32_t elasped_time(uint32_t const start)
{
    uint32_t const now = systick_get();
    return now - start;
}
#define BENCHMARK(elasped)                                                     
    for (                                                                      
        struct {                                                               
            uint8_t done;                                                      
            uint32_t start;                                                    
        } __metadata = {0, systick_get()};                                     
        !__metadata.done;                                                      
        ((elasped) = elasped_time(__metadata.start)), __metadata.done = 1)
int main(void)
{
    uint32_t time = 0;
    BENCHMARK(time)
    {
        int i = 0; //< Something you want to benchmark
    }
    printf("Time = %dn", time);
    return 0;
}

以下是BENCHMARK()宏在消耗时的外观(使用 gcc -E (

int main(void) {
    uint32_t time = 0;
    for (
        struct {
            uint8_t done;
            uint32_t start;
        } __metadata = {0, systick_get()};
        !__metadata.done;
        ((time) = elasped_time(__metadata.start)), __metadata.done = 1)
    {
        int i = 0; //< Something you want to benchmark
    }
    printf("Time = %dn", time);
    return 0;
}

愿丹尼斯·里奇原谅我们。