Variable declaration reset: Difference between revisions

C++ implmentation
No edit summary
(C++ implmentation)
Line 83:
}</lang>
<small>(Note: Obviously the <code>for (int i=0, prev</code> needs the outer i and the inner prev removed, and the same "int" added to the second loop, for it to compile cleanly though it only does so under C99 (or later) as for loop initial declarations are not allowed in C89/90.)</small>
{{out}}
<pre>
2
5
</pre>
 
=={{header|C++}}==
<lang cpp>#include <array>
#include <iostream>
 
int main()
{
constexpr std::array s {1,2,2,3,4,4,5};
 
// declare a variable outside of the loop to hold the previous value. At
// this point it is undefined which is OK as long as it is set before
// it is used.
int previousValue;
 
for(size_t i = 0; i < s.size(); ++i)
{
// in C++, variables in block scope are reset at each iteration
const int currentValue = s[i];
 
if(i > 0 && previousValue == currentValue)
{
std::cout << i << "\n";
}
previousValue = currentValue;
}
}
</lang>
{{out}}
<pre>
125

edits