mercredi 1 février 2017

Are all statements inside a switch without a case will be skipped?

I have this example which is about the use of switch and if:

int main(int argc, char** argv) {

    int i = 0, j = 1;

    switch(i){
        if (!i) // will not be evaluated!
            std::cout << "if(!i) : i = 0" << std::endl;

        if (1 == i) // no magic it will not be evaluated.
            std::cout << "i = 1" << std::endl;

        if (1 == j) // will not be evaluated!
            std::cout << "if(j == 1) : j = 1" << std::endl;

        for (int k(0); k < 3; k++) //  will not be evaluated!
            std::cout << "Ok!" << std::endl;

        while (1) //  will not be evaluated!
            std::cout << "Hi" << std::endl;

        case 0: // ok as we guess no magic
            std::cout << "(case 0) : i = 0" << std::endl;
        break;

        default: // now everything belongs to a `case` as we think it will be evaluated.
        if (1 == i)
            std::cout << "(default: if(i == 1)) : i = 1" << std::endl;
        if (1 == j) // ok
            std::cout << "(default: if(j == 1)) : j = 1" << std::endl;
    }


    std::cout << std::endl;
    std::cin.get();
    return 0;
}

  • So the program above uses ifs instead of cases the thing that matters why if inside a switch will not be evaluated?? Also why they are evaluated only in a case? Like in default:?

  • Does this mean that all statements will be skipped without a case? - If so why new C++ doesn't prevent that as long as they are redundant?

Aucun commentaire:

Enregistrer un commentaire