Code: Select all
static string words[]
static string numToStr(int num)
"static" is a pretty awful keyword in C++ due to its several unrelated uses. You don't need it here, as it doesn't accomplish anything that your program will care about. It means, in a nutshell: "only this file can use this function/variable, and no one else can, even if you use the 'extern' keyword". (This is called "internal linkage".)
In Java, these functions were part of a class. In that instance, the "static" keyword means "I do not need an instance of the class in order to call these functions/use these variables". They only exist once. Because the C++ versions are not in a class, the meaning is completely different.
Confusing!
Code: Select all
int lengthOfWords = sizeof(words) / sizeof(words[0]) - 1;
The "sizeof" operator (yes, it's an operator, just like + or -, but it cannot be overloaded) always does the exact same thing: gives you the number of bytes of the
type of whatever you pass in (you can also just pass in a type: like
sizeof(int)).
"words" here has a type of
string[51] (the compiler automatically fills in that 51 based on the number of elements specified in the initializer list). This can be a bit surprising, that the number of elements is part of the type itself: that
string[5] and
string[6] are as different to the compiler as
int and
float are. (Of course they can both be intrinsically coerced to a
string*, so perhaps they're not
as different.)
The point remains: the
sizeof(string[51]) is
51*sizeof(string), so if you divide by
sizeof(string), they cancel out and you're left with 51. Can you see why
sizeof(words[0]) is equivalent to
sizeof(string)?
However, "lengthOfWords" is a very bad name here, because you're not storing the length of the words array, which is 51. You're storing 50. It should be named "maxNumber" or something.
Also--don't feel like you need to use exceptions to handle error cases, at least in C++. It is just one way to go about it, and many projects do not use them at all. UE3/UE4 don't.