Table of Contents
How to use range-based for loop in C
Use references to avoid unnecessary copying
Notes and common mistakes
Home Backend Development C++ C range-based for loop tutorial

C range-based for loop tutorial

Jul 27, 2025 am 12:49 AM
c++

C's range-based for loop improves code readability and reduces errors by simplifying syntax. Its basic structure is for (declaration : range), which is suitable for arrays and STL containers, such as traversing int arr[] or std::vector vec. Using references (such as const std::string& name) can avoid copy overhead and can modify element content. Notes include: 1. Do not modify the container structure in the loop; 2. Ensure that the range is effective and avoid the use of freed memory; 3. There is no built-in index and requires manual maintenance of the counter. Mastering these key points allows you to use this feature efficiently and safely.

C range-based for loop tutorial

It is a simple and safe way to traverse an array or container using a range-based for loop in C. It was introduced from C 11, saving the hassle of writing loop conditions and indexing variables, making the code clearer and easier to read.

C range-based for loop tutorial

Here are some practical usage scenarios and precautions that you may be concerned about.

C range-based for loop tutorial

How to use range-based for loop in C

The basic syntax is as follows:

 for (declaration : range) {
    // Perform an action}

Here declaration is a reference or copy of the element in each iteration, and range is an array, container, or any object that supports begin() and end() .

C range-based for loop tutorial

For example, iterate over an integer array:

 int arr[] = {1, 2, 3, 4, 5};
for (int num : arr) {
    std::cout << num << " ";
}

The output result is: 1 2 3 4 5

This method also applies to STL containers, such as vector:

 std::vector<int> vec = {10, 20, 30};
for (int val : vec) {
    std::cout << val << " ";
}

Use references to avoid unnecessary copying

If you are dealing with larger objects or structures, it is recommended to use reference methods to avoid copy overhead:

 std::vector<std::string> names = {"Alice", "Bob", "Charlie"};
for (const std::string& name : names) {
    std::cout << name << std::endl;
}

const is added here because we do not intend to modify the original data, but only perform read operations. If you really need to modify the element, you can remove const :

 for (std::string& name : names) {
    name = "_modified";
}

This allows you to directly modify the contents in the container.


Notes and common mistakes

There are several details that are prone to errors and need to be noted:

  • Do not modify container structure in range-based for
    For example, elements cannot be deleted when traversing vectors, which will lead to undefined behavior. This situation should be looped with a traditional iterator.

  • Make sure range is valid
    If the incoming is a temporary object or a freed memory area, it may crash. For example:

     const int* getArray() {
        int arr[] = {1, 2, 3};
        return arr; // Return local variable pointer, unsafe}
    
    for (int x : getArray()) {} // Error! arr has expired
  • Cannot get the current index position
    Scope-based for loops do not have built-in index variables. If you need to know which element is currently, you have to maintain a counter yourself.


  • Basically that's it. Once you master these points, you can use range-based for in most cases to write clean and efficient loop logic.

    The above is the detailed content of C range-based for loop tutorial. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1504
276
C   fold expressions example C fold expressions example Jul 28, 2025 am 02:37 AM

C folderexpressions is a feature introduced by C 17 to simplify recursive operations in variadic parameter templates. 1. Left fold (args...) sum from left to right, such as sum(1,2,3,4,5) returns 15; 2. Logical and (args&&...) determine whether all parameters are true, and empty packets return true; 3. Use (std::cout

C   char array to string example C char array to string example Aug 02, 2025 am 05:52 AM

The answer is: Use the std::string constructor to convert the char array to std::string. If the array contains the intermediate '\0', the length must be specified. 1. For C-style strings ending with '\0', use std::stringstr(charArray); to complete the conversion; 2. If the char array contains the middle '\0' but needs to convert the first N characters, use std::stringstr(charArray,length); to clearly specify the length; 3. When processing a fixed-size array, make sure it ends with '\0' and then convert it; 4. Use str.assign(charArray,charArray strl

C   find in vector example C find in vector example Aug 02, 2025 am 08:40 AM

The most common method of finding vector elements in C is to use std::find. 1. Use std::find to search with the iterator range and target value. By comparing whether the returned iterator is equal to end(), we can judge whether it is found; 2. For custom types or complex conditions, std::find_if should be used and predicate functions or lambda expressions should be passed; 3. When searching for standard types such as strings, you can directly pass the target string; 4. The complexity of each search is O(n), which is suitable for small-scale data. For frequent searches, you should consider using std::set or std::unordered_set. This method is simple, effective and widely applicable to various search scenarios.

What are the correct launch.json settings for debugging a C   application with GDB on Linux? What are the correct launch.json settings for debugging a C application with GDB on Linux? Aug 04, 2025 am 03:46 AM

TodebugaC applicationusingGDBinVisualStudioCode,configurethelaunch.jsonfilecorrectly;keysettingsincludespecifyingtheexecutablepathwith"program",setting"MIMode"to"gdb"and"type"to"cppdbg",using"ex

C   endianness check example C endianness check example Jul 30, 2025 am 02:30 AM

The system endianness can be detected by a variety of methods, the most commonly used is the union or pointer method. 1. Use a union: Assign uint32_t to 0x01020304, if the lowest address byte is 0x04, it is a small endian, and if it is 0x01, it is a big endian; 2. Use pointer conversion: Assign uint16_t to 0x0102, read the byte order through the uint8_t pointer, [0]==0x02 and [1]==0x01 is a small endian, otherwise it is a big endian; 3. Compilation-time detection: define the constexpr function to determine whether the (char)&int variable is 1, and combine ifconstexpr to determine the endian order during the compilation period; 4. Runtime macro encapsulation: use (char*)&amp

C   mutex example C mutex example Aug 03, 2025 am 08:43 AM

std::mutex is used to protect shared resources to prevent data competition. In the example, the automatic locking and unlocking of std::lock_guard is used to ensure multi-thread safety; 1. Using std::mutex and std::lock_guard can avoid the abnormal risks brought by manual management of locks; 2. Shared variables such as counters must be protected with mutex when modifying multi-threads; 3. RAII-style lock management is recommended to ensure exception safety; 4. Avoid deadlocks and multiple locks in a fixed order; 5. Any scenario of multi-thread access to shared resources should use mutex synchronization, and the final program correctly outputs Expected:10000 and Actual:10000.

C   Boost library example C Boost library example Jul 30, 2025 am 01:20 AM

Install the Boost library, 2. Write code for DNS resolution using Boost.Asio, 3. Compile and link the boost_system library, 4. Run the program to output the IP address parsed by www.google.com; this example shows how Boost.Asio simplifies network programming in C, implements cross-platform, type-safe synchronous DNS queries through io_context and tcp::resolver, and supports IPv4 and IPv6 address resolution, and finally prints all resolution results.

C   erase from vector while iterating C erase from vector while iterating Aug 05, 2025 am 09:16 AM

If it is iterating when deleting an element, you must avoid using a failed iterator. ①The correct way is to use it=vec.erase(it), and use the valid iterator returned by erase to continue traversing; ② The recommended "erase-remove" idiom for batch deletion: vec.erase(std::remove_if(vec.begin(),vec.end(), condition), vec.end()), which is safe and efficient; ③ You can use a reverse iterator to delete from back to front, the logic is clear, but you need to pay attention to the condition direction. Conclusion: Always update the iterator with the erase return value, prohibiting operations on the failed iterator, otherwise undefined behavior will result.

See all articles