Variable declaration reset: Difference between revisions

Content added Content deleted
(C++ implmentation)
(C++ update)
Line 97: Line 97:
constexpr std::array s {1,2,2,3,4,4,5};
constexpr std::array s {1,2,2,3,4,4,5};


if(!s.empty())
// 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)
{
{
int previousValue = s[0];
// in C++, variables in block scope are reset at each iteration
const int currentValue = s[i];


if(i > 0 && previousValue == currentValue)
for(size_t i = 1; i < s.size(); ++i)
{
{
// in C++, variables in block scope are reset at each iteration
std::cout << i << "\n";
const int currentValue = s[i];

if(i > 0 && previousValue == currentValue)
{
std::cout << i << "\n";
}

previousValue = currentValue;
}
}
previousValue = currentValue;
}
}
}
}

</lang>
</lang>
{{out}}
{{out}}