Why is my use of the ?: conditional operator incorrect?

前端 未结 4 891
广开言路
广开言路 2021-01-22 07:09

I get a compilation error while trying to compile, \"not a statement\", and the code is:

(checkDatabaseExist())?connectToDB() : buildDB();

when

4条回答
  •  日久生厌
    2021-01-22 07:33

    Yes, you can't use the conditional operator like that. It's intended to compute one expression or another as a result. It's not intended to be a way of choosing one statement to execute or another.

    Just use:

    if (checkDatabaseExist()) {
        connectToDB();
    } else {
        buildDB();
    }
    

提交回复
热议问题