I am confused about variable scope and would like to better understand it.
Moved cout oddS and cout evenS to outside for loop. Code executes properly. If moved inside for loop, code executes with improper values for oddS and evenS.
#include <iostream>
#include <vector>
#include <cmath>
int main()
{
double evenS, oddS, pH = 0;
std::vector<double> v1 = {2, 4, 3, 6, 1, 9};
for(int i = 0; i < v1.size(); i++)
{
pH = v1[i];
if(fmod(pH, 2) == 0)
{
evenS = evenS + v1[i];
}
else if(fmod(pH, 2) == 1)
{
oddS = oddS + v1[i];
}
}
std::cout << evenS << "\n";
std::cout << oddS << "\n";
}
I was expecting the oddS and evenS to not hold the proper values if incremented outside of the for loop. However, the contrary is true, which produced my confusion.