Code:
int count_char(const char *stringToSearch, int letterCounts[26])
{
for (size_t i = 0; stringToSearch[i]; ++i)
{
// Convert the charactors to their uppercase equivelents.
int val = toupper(stringToSearch[i]);
letterCounts[val - 'A'] += 1;
}
return 0;
}
OK ignoring that it went overboard for a trivial C++ assignment. I wanted to try and clarify something. Having int val = ... inside the loop is the same as having it declared before the loop only because it is a basic type of a fixed size. If val was some class that allocated memory this would not be the case because I believe val would be constructed and destructed each pass through the loop, thus slowing it down. That being the case would it not be better to always define the class before the loop in case later val gets changed from int to myCoolInt class or something.
Code:
class Test{
public:
Test(int i) {c = new char[i];}
~Test() {delete[] c;}
int x;
char* c;
};
int main()
{
for(int i=0; i<5; ++i)
{
Test t(10);
t.x = i;
}
return 0;
}
vs
Code:
class Test{
public:
Test(int i) {c = new char[i];}
~Test() {delete[] c;}
int x;
char* c;
};
int main()
{
Test t(10);
for(int i=0; i<5; ++i)
{
t.x = i;
}
return 0;
}
Looking at the assembly from the above seems to support what I said.