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

3

How can I create an algorithm in C++ (using Qt ) to abort processing of the following codes?

I have to validate many different entries and I do not want to be creating if else if else . It gets ugly from the code.

Example, but 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
}
    
asked by anonymous 17.03.2014 / 17:59

1 answer

8

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

In functions you can use 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 early as possible leaves the code more readable as it eliminates these cases from the main algorithm.

Another alternative is to throw 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
}
    
17.03.2014 / 19:10