Pointer is undefined
I'm trying to learn C++ out of a book. One of the examples is:
string s("some string");
if (s.begin() != s.end())
auto it = s.begin();
*it == toupper(*it);
When I put this into Visual Studio, I receive an error declaring that *it
is undefined and it won't compile.
I know this is probably the most basic thing of all time, I'm just trying to understand why it's undefined. Is this just a bad example for a pointer to an iterator?
Solution 1:
it
is declared as a local variable inside of the if
block. It goes out of scope once the if
block exits. So, in your example, it
doesn't exist anymore in the toupper()
operation.
Even if it did exist, the code would be dereferencing the end
iterator if the string were empty (begin
and end
were the same), which is undefined behavior.
You need to add curly braces to the if
block so you can then move the toupper()
operation inside the block, where it
is still in scope.
Also, ==
is a comparison operator. If the goal is it modify the string, you need to use the =
assignment operator instead.
Try this:
string s("some string");
if (s.begin() != s.end()) {
auto it = s.begin();
*it = toupper(*it);
}