element14 Community
element14 Community
    Register Log In
  • Site
  • Search
  • Log In Register
  • Community Hub
    Community Hub
    • What's New on element14
    • Feedback and Support
    • Benefits of Membership
    • Personal Blogs
    • Members Area
    • Achievement Levels
  • Learn
    Learn
    • Ask an Expert
    • eBooks
    • element14 presents
    • Learning Center
    • Tech Spotlight
    • STEM Academy
    • Webinars, Training and Events
    • Learning Groups
  • Technologies
    Technologies
    • 3D Printing
    • FPGA
    • Industrial Automation
    • Internet of Things
    • Power & Energy
    • Sensors
    • Technology Groups
  • Challenges & Projects
    Challenges & Projects
    • Design Challenges
    • element14 presents Projects
    • Project14
    • Arduino Projects
    • Raspberry Pi Projects
    • Project Groups
  • Products
    Products
    • Arduino
    • Avnet & Tria Boards Community
    • Dev Tools
    • Manufacturers
    • Multicomp Pro
    • Product Groups
    • Raspberry Pi
    • RoadTests & Reviews
  • About Us
  • Store
    Store
    • Visit Your Store
    • Choose another store...
      • Europe
      •  Austria (German)
      •  Belgium (Dutch, French)
      •  Bulgaria (Bulgarian)
      •  Czech Republic (Czech)
      •  Denmark (Danish)
      •  Estonia (Estonian)
      •  Finland (Finnish)
      •  France (French)
      •  Germany (German)
      •  Hungary (Hungarian)
      •  Ireland
      •  Israel
      •  Italy (Italian)
      •  Latvia (Latvian)
      •  
      •  Lithuania (Lithuanian)
      •  Netherlands (Dutch)
      •  Norway (Norwegian)
      •  Poland (Polish)
      •  Portugal (Portuguese)
      •  Romania (Romanian)
      •  Russia (Russian)
      •  Slovakia (Slovak)
      •  Slovenia (Slovenian)
      •  Spain (Spanish)
      •  Sweden (Swedish)
      •  Switzerland(German, French)
      •  Turkey (Turkish)
      •  United Kingdom
      • Asia Pacific
      •  Australia
      •  China
      •  Hong Kong
      •  India
      • Japan
      •  Korea (Korean)
      •  Malaysia
      •  New Zealand
      •  Philippines
      •  Singapore
      •  Taiwan
      •  Thailand (Thai)
      • Vietnam
      • Americas
      •  Brazil (Portuguese)
      •  Canada
      •  Mexico (Spanish)
      •  United States
      Can't find the country/region you're looking for? Visit our export site or find a local distributor.
  • Translate
  • Profile
  • Settings
Code Exchange
  • Technologies
  • More
Code Exchange
Blog modern C++ for loop, but you still want an index
  • Blog
  • Forum
  • Documents
  • Events
  • Polls
  • Files
  • Members
  • Mentions
  • Sub-Groups
  • Tags
  • More
  • Cancel
  • New
Join Code Exchange to participate - click to join for free!
  • Share
  • More
  • Cancel
Group Actions
  • Group RSS
  • More
  • Cancel
Engagement
  • Author Author: Jan Cumps
  • Date Created: 5 Nov 2025 9:08 PM Date Created
  • Views 225 views
  • Likes 8 likes
  • Comments 7 comments
  • Modern C++
  • c++26
Related
Recommended

modern C++ for loop, but you still want an index

Jan Cumps
Jan Cumps
5 Nov 2025

C++ has a range loop. A for loop that will run over all elements in the range you give it:

std::vector<int> v = {0, 1, 2, 3, 4, 5};
// ...

    for (auto i : v)
        std::cout << i << ' ';
    std::cout << '\n';

You don't have to check for container size. The for loop will give you the next item in i, contained in v, at each loop execution. start to end.
At runtime, this loop is as performant as the traditional C loop. You don't need to index the item in the range yourself, and it's overflow safe.

But there are times where you use the old school index for something else. Maybe to print rows:

int myNumbers[] = {25, 50, 75, 100};

int length = sizeof(myNumbers) / sizeof(myNumbers[0]);
int i;

for (i = 0; i < length; i++) {
  printf("%d %d\n", i, myNumbers[i]);
}

The range for loop doesn't have an index. But if you need one, it's not hard to create one. The new construct has an initialiser clause you can use. The advantage of that initialiser is, that the variable you declare there, is not visible outside the loop. No scope leakage:

std::vector<int> v = {0, 1, 2, 3, 4, 5};

    for (size_t inx = 0; auto i : v)
        std::cout << inx++ << ": " << i << ' ';
    std::cout << '\n';

Just a little code snippet that gives you all of the range for loop, and gives you that counter if you need it.
Thank you for reading.

  • Sign in to reply
Parents
  • Stuart_S
    Stuart_S 25 days ago

    Is the 'auto' keyword valid in basic C, I might give it a shot on the old DevCPP

    • Cancel
    • Vote Up 0 Vote Down
    • Sign in to reply
    • More
    • Cancel
  • Jan Cumps
    Jan Cumps 25 days ago in reply to Stuart_S

    Auto in c has a different meaning and purpose than auto in c++.

    The below answer is AI generated. It gives a fair summary:

    No, the auto keyword in C and C++ are not the same, especially since C++11. In C, auto is a storage class specifier that indicates a variable has an "automatic" storage duration (local to a scope), but it is a relic and rarely used because stack allocation is the default. In modern C++, auto is a type-deduction specifier, meaning the compiler automatically deduces the type of a variable from its initializer. 
    C auto keyword
    • Meaning: Indicates automatic storage duration, meaning the variable is local to its scope (e.g., a function) and is allocated on the stack.
    • Usage: It is almost always redundant because automatic storage is the default behavior for local variables, so it's rarely used.
    • Type: Does not perform type inference. 
    C++ auto keyword
    • Meaning: Performs type deduction, where the compiler infers the type of a variable from the initializer expression used to declare it.
    • Usage: Used to write cleaner code, especially with complex or long types, and can help reduce boilerplate code.
    • Type: Performs type inference. For example, auto x = 5; declares x as an int, while auto y = 1.5; declares y as a double. 

    In the context of my example, it's used as type deduction. The compiler knows that my container contains ints. So it will create a variable i of type int.

    • Cancel
    • Vote Up 0 Vote Down
    • Sign in to reply
    • More
    • Cancel
  • Stuart_S
    Stuart_S 24 days ago in reply to Jan Cumps

    I get it now, you've used the 'auto' to declare the 'for' loop count index variable type instead of say a 'char' or 'int'

    • Cancel
    • Vote Up 0 Vote Down
    • Sign in to reply
    • More
    • Cancel
  • Jan Cumps
    Jan Cumps 24 days ago in reply to Stuart_S

    Yes. In both cases below, the auto i translates in an int i variable. Because that's the type contained in the vector v.

    If you don't need an index/counter in your code (the normal case), you only need auto i:

    for (auto i : v) {
      // i (an int variable) will get the next value in the vector v at each loop
      // first loop it will have the value of element 1, 2nd loop element 2, ...
      // until all elemens in the loop have been used
      std::cout << i << " "; // this will print each value contained in the vector, with a space in between
    }

    If you need an index / counter for some reason (in my case, because I want use it in the log output), you can declare and initialise a variable for that in the for loop definition.   In this case, I chose the name inx for that variable.

    I am responsible myself to increment it in the loop. The range for loop doesn't increment anything itself:

    for (size_t inx = 0; auto i : v) {
      std::cout << inx++ // I print the index, then increment it. First loop this is 0 (the initialised value, then 1, then 2 ...
        << ": " << i << " "; // then I print the auto i, just like in the example above
    }

    Hope it makes sense.

    If you have a recent C++ compiler (supporting C++11 or later), you can try it out. Here's a complete file:

    #include <iostream>
    #include <vector>
    #include <ranges>
    
    int main()
    {
        std::vector<int> v = {10, 21, 32, 43, 54, 65};
        
        for (auto i : v) { // access by value, the type of i is int
            std::cout << i << ' ';
        }
        std::cout << '\n';
    
        for (size_t inx = 0; auto i : v) { // access by value, the type of i is int
            std::cout << inx++ << ": " << i << ' ';
        }
        std::cout << '\n';
    }

    expected output:

    10 21 32 43 54 65 
    0: 10 1: 21 2: 32 3: 43 4: 54 5: 65
    • Cancel
    • Vote Up 0 Vote Down
    • Sign in to reply
    • More
    • Cancel
Comment
  • Jan Cumps
    Jan Cumps 24 days ago in reply to Stuart_S

    Yes. In both cases below, the auto i translates in an int i variable. Because that's the type contained in the vector v.

    If you don't need an index/counter in your code (the normal case), you only need auto i:

    for (auto i : v) {
      // i (an int variable) will get the next value in the vector v at each loop
      // first loop it will have the value of element 1, 2nd loop element 2, ...
      // until all elemens in the loop have been used
      std::cout << i << " "; // this will print each value contained in the vector, with a space in between
    }

    If you need an index / counter for some reason (in my case, because I want use it in the log output), you can declare and initialise a variable for that in the for loop definition.   In this case, I chose the name inx for that variable.

    I am responsible myself to increment it in the loop. The range for loop doesn't increment anything itself:

    for (size_t inx = 0; auto i : v) {
      std::cout << inx++ // I print the index, then increment it. First loop this is 0 (the initialised value, then 1, then 2 ...
        << ": " << i << " "; // then I print the auto i, just like in the example above
    }

    Hope it makes sense.

    If you have a recent C++ compiler (supporting C++11 or later), you can try it out. Here's a complete file:

    #include <iostream>
    #include <vector>
    #include <ranges>
    
    int main()
    {
        std::vector<int> v = {10, 21, 32, 43, 54, 65};
        
        for (auto i : v) { // access by value, the type of i is int
            std::cout << i << ' ';
        }
        std::cout << '\n';
    
        for (size_t inx = 0; auto i : v) { // access by value, the type of i is int
            std::cout << inx++ << ": " << i << ' ';
        }
        std::cout << '\n';
    }

    expected output:

    10 21 32 43 54 65 
    0: 10 1: 21 2: 32 3: 43 4: 54 5: 65
    • Cancel
    • Vote Up 0 Vote Down
    • Sign in to reply
    • More
    • Cancel
Children
  • Stuart_S
    Stuart_S 23 days ago in reply to Jan Cumps

    Clear as mud now, thankyou!

    • Cancel
    • Vote Up 0 Vote Down
    • Sign in to reply
    • More
    • Cancel
element14 Community

element14 is the first online community specifically for engineers. Connect with your peers and get expert answers to your questions.

  • Members
  • Learn
  • Technologies
  • Challenges & Projects
  • Products
  • Store
  • About Us
  • Feedback & Support
  • FAQs
  • Terms of Use
  • Privacy Policy
  • Legal and Copyright Notices
  • Sitemap
  • Cookies

An Avnet Company © 2025 Premier Farnell Limited. All Rights Reserved.

Premier Farnell Ltd, registered in England and Wales (no 00876412), registered office: Farnell House, Forge Lane, Leeds LS12 2NE.

ICP 备案号 10220084.

Follow element14

  • X
  • Facebook
  • linkedin
  • YouTube