How can I do a Goto in c++?
Printable View
How can I do a Goto in c++?
you jump to a label lbl:
goto lbl;
you declare a label lbl:
lbl:
Why do you need goto? If you don't know how to code algorims in general, avoid goto at all cost, if you want to go low level use of goto is ok. There's some selective cases where a goto would be a lot cleaner, but in general it's recommended for other than advanced programmers.
Im going a basic comsole thing; since i dont know error stuff yet, it check if the entered data is right, if not, goto some label.
Im still learning :D
Aaaaaaccckkkkk :eek:Quote:
Originally posted by markman
Im going a basic comsole thing; since i dont know error stuff yet, it check if the entered data is right, if not, goto some label.
Im still learning :D
Read the input.
If it's not valid, throw an exception :p
Is that a c++ term?Quote:
Originally posted by parksie
exception
Yep. The idea is that rather than errors being either handled too early or having to be manually propagated, you just throw an exception and the system unwinds the function call stack searching for a compatible catch block to handle the exception. If nothing catches it, then the system closes the program down.
So, library functions can throw exceptions, and it's a lot simpler to handle for you. For example:The point here, is that if new fails to allocate the memory, it throws an exception of type bad_alloc (standard class, derives from exception). This doesn't have to be caught by somecode, but main catches it. It means that exceptions are handled at a higher level, by handler code that understands more of the application, and therefore what the best solution to resolve the problem is.Code:int* mynew(int count) {
int *ptr = new int[count];
for(int i = 0; i < count; ++i)
ptr[i] = -1;
return ptr;
}
void somecode() {
int *ptr = mynew(50);
// Do some processing
}
int main() {
try {
somecode();
} catch(exception &ex) {
// Standard library exceptions all derive from exception
cout << somecode.what() << endl;
} catch(...) {
// ALL exceptions will be matched by this
cout << "Other exception" << endl;
}
return 0;
}
NB: Anything can be thrown, for example an int.
Read Thinking in C++ for more information :)