Namespaces
Variants

C++ keyword: for

From cppreference.net
C++ language
General topics
Flow control
Conditional execution statements
Iteration statements (loops)
Jump statements
Functions
Function declaration
Lambda function expression
inline specifier
Dynamic exception specifications ( until C++17* )
noexcept specifier (C++11)
Exceptions
Namespaces
Types
Specifiers
constexpr (C++11)
consteval (C++20)
constinit (C++20)
Storage duration specifiers
Initialization
Expressions
Alternative representations
Literals
Boolean - Integer - Floating-point
Character - String - nullptr (C++11)
User-defined (C++11)
Utilities
Attributes (C++11)
Types
typedef declaration
Type alias declaration (C++11)
Casts
Memory allocation
Classes
Class-specific function properties
Special member functions
Templates
Miscellaneous

用法

  • for 循环:作为循环的声明
  • 基于范围的 for 循环:作为循环的声明
(自 C++11 起)

示例

#include <iostream>
int main() noexcept
{
    // 以下 'for' 循环语句:
    // 1. (初始化语句) 声明名为 'i' 的整数并将其初始化为值 '0'
    // 2. (条件)       检查 i 是否小于 3,若不满足则终止循环执行
    // 3. (语句)       将整数 'i' 的当前值输出到 stdout
    // 4. (表达式)     对整数 'i' 进行前置递增(将其值增加 1)
    // 5.              返回第 2 步(条件判断)
                                // 初始化语句: int i{0};
                                // 条件:       i < 3
    for (int i{0}; i < 3; ++i)  // 表达式:      ++i
        std::cout << i;         // 语句:       std::cout << i;
}

输出:

012

参见

(自 C++17 起)
(自 C++23 起)
(自 C++20 起)