是否可以在 C/C++ 中 for 循环的增量部分执行多个操作
Is it possible to do multiple operations in increment part of for loop in C/C++?
是否可以在 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;
}
愿丹尼斯·里奇原谅我们。
相关文章:
- 在执行其他功能的同时播放动画(LED矩阵和Arduino/ESP8266)
- C++,系统无法执行指定的程序
- 使用C++中的模板和运算符重载执行矩阵运算
- 创建一个函数以在输入为负数或零时输出字符串.第一次执行用户定义的函数
- 执行函数时导致崩溃的变量
- 无论条件是否为true,if总是在c++中执行
- 当函数模板参数是具有默认参数的类模板时,函数模板参数的推导如何执行
- 有没有办法将谓词中的元素偏移量传递给 std 算法?
- 在C++中对T*类型执行std::move的意外行为
- 使用QProcess执行命令,并将结果存储在QStringList中
- 如何在没有信号的情况下从C++执行QML插槽
- 如何确认我的constexpr表达式实际上已经在编译时执行
- C++17中的并行执行策略
- QML按钮点击功能执行顺序
- 程序在执行程序的其余部分之前退出
- 为什么catch中的代码没有被执行
- 使用Pybind11向Python公开Eigen::张量
- 张量流错误:执行器无法创建内核。没有注册'Snapshot' 适用于 GPU 设备的 OpKernel 运行图像标签示例
- C++ 将部分数组(在某些偏移量)转换为其他类型
- c++11用户定义的字面量,与编译/执行二分法冲突