How can I translate a loop like the below one to C style?
for (auto element : vector) {
Do_Somethin();
}
How can I translate a loop like the below one to C style?
for (auto element : vector) {
Do_Somethin();
}
You'd start with converting it to a non-ranged-based for loop.
{
auto&& range = Chains;
using std::begin; using std::end; // possibly cbegin/cend
auto it = begin(range); // possibly cbegin
auto end = end(range); // possibly cend
for(; it!=end; ++it) {
auto block = *it;
// body of loop
}
}
then you tease apart each piece.
Start by deducing what the auto
variables are. Guess if you have to, then do a static_assert( std::is_same_v< decltype(begin), your_guess > );
to confirm. Once you have confirmed, replace. DO NOT guess and swap in the type and assume "it compiles, I got it right"; that can lead to subtle bugs.
Then replace begin
and end
with an equivalent expression. You'll have to do some research (it could be raw pointers into arrays, or it could be .begin
methods, or it could be a free begin
function in the namespace of the range expression).
What happens next depends on what your iterators are here. Are they plain pointers? If so, the problem is probably pretty easy. If not, you have more work to do.
Finally, remove all references, and then tidy up.
Ideally you'd want to do each of these steps as a git commit with unit tests confirming no change of behavior. You appear not to be qualified to make these changes without such testing. That is ok, and the unit testing will have value.
Going the other way, there are C++ to C translators. They will generate unreadable and unmaintainable code in practice.
But the output can be compiled by a C compiler.
Yes, you can always exchange ranged-for for a classic for loop.
For ranged-for to work, Chains
must be of a type that implements an iterator interface, or must be an array.
If it's an array, you know what to do.
Otherwise, you can write the loop as:
for (auto it = Chains.begin(), end = Chains.end(); it != end; ++it)
{
auto block = *it;
Do_Somethin();
}
(Though, possibly, you may need cbegin()
if only a const interface is available and begin()
has no const
overload for some reason.)
If the type of Chains
supports random access with operator[]
, you could also try something like this:
for (std::size_t i = 0; i < Chains.size(); ++it)
{
auto block = Chains[i];
Do_Somethin();
}
… though you'll need to look at the documentation to find out what .size()
should actually be.
Now of course C doesn't have iterators, or auto
, but then it doesn't have classes either. You can choose to substitute replacements for those features as well if you like.