I'm trying to check a list if something is already stored in it, and add it if it is not. If it doesn't exist, the goto statement jumps over the code that stores it in the list.
I keep getting the error
initialization of 'a' is skipped by 'goto exists'
I could probably put the initialization part before the loop, but is there a way to not initialize at all? Since it's not being used, why initialize it right?
1 2 3 4 5 6 7 8 9 10
for ( list<mytype>::const_iterator Iter = list1->cbegin(); Iter != list1->cend(); Iter++ )
{
if ( ( strcmp( Name, Iter->name.c_str() ) == 0 ) || ( strcmp( SName, Iter->sname.c_str() ) == 0 ) )
{
goto exists;
}
}
mytype a = { string( Name ), string( SName ) };
list1->push_back( a );
exists:
Don't use a goto for this, there are times and places to use a goto but this is not one of them. Try avoiding them when you are learning.
Try using a while loop that escapes the loop when you have reached the end OR if the list already contains the element and then break; from the loop (but not until after you set a flag that says the element already 'exists'.
Then after the loops check if it exists, here I will give you a piece of the code:
1 2 3 4 5 6 7 8 9 10 11 12
bool exists = false;
//... setup iterator
while(Iter != list1->cend())
{
//... do stuff while not found or not end of list
}
if(!exists)
{
mytype a = { string( Name ), string( SName ) };
list1->push_back( a );
}