Command to exit the scope of a function (`break`equivalent)

Asked

Viewed 4,156 times

3

How can I create an algorithm in C++ (using Qt) to abort code processing?

I have to validate many different entries and I don’t want to keep creating if else if else. The code is ugly.

Example, but the IDE returns error in break :

if(!price()){
  QMessageBox ...erro preco;
  break; ///Termina o código. 
}
if(!date()){
  QMessageBox ...erro data;
  break; ///Termina o código. 
}

///insert etc...///


bool window::price(){
 true or false
}

bool window::date(){
 true or false
}
  • 2

    Would not be return where is break? You could complete the code you posted.

  • @Lucas Nunes: No. because if is in the builder.

  • You can give return in a manufacturer (in function void), no problem. Just write return;.

  • Blz. Thank you :)

1 answer

8


break is only valid to make the execution flow out of a loop (for, while or do-while) or a switch-case.

In functions you can use a return:

if (!price()) {
  QMessageBox( ... );
  return; 
}
if (!date()) {
  QMessageBox( ... );
  return; 
}

//Algoritmo principal
...

This is a widely used pattern. Checking for special conditions and eliminating them as soon as possible makes the code more readable as it eliminates these cases from the main algorithm.

Another alternative is to make an exception. This alternative is particularly interesting if the code in question is in the constructor of an object. This way the object is never created in an invalid state;

//Construtor
Object(Arg1 a1, Arg2 a2) attrib1(a1), attrib2(a2) {
    if (!price()) {
        throw InvalidPrice();
    }
    if (!date()) {
        throw InvalidDate();
    }
    //Se chegou até aqui o objeto é válido, continua a inicialização dele
    ...
}

Using the object:

try {
    Object obj(arg1, arg2);
    //Se passou do construtor, o objeto é 100% válido
    obj.use();
}
catch (InvalidPrice const &) {
    QMessageBox( ... ); //Avisa sobre preço inválido
}
catch (InvalidDate const &) {
    QMessageBox( ... ); //Avisa sobre data inválida
}
  • @C. E. Gesser Blz. Thank you very much for your help.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.