Difference between switch and if

Source: Internet
Author: User

[Switch] the difference between switch and if

If it is purely a number or character, we recommend that you use switch, because it will only retrieve the variable value once in the start switch brackets, and then compare this value with the case set below, however, if you use the if clause, You must retrieve the variable value every time you encounter a conditional clause. The difference in efficiency is here. For example:

If (A = 1)
//...
Else if (a = 2)
//...
Else if (a = 3)
//...

In the worst case, when a = 3, this program fragment requires three comparisons, and the value of variable A must be retrieved once for each comparison. Switch:

Switch ()
{
Case 1:
//...
Break;
Case 2:
//...
Break;
Case 3:
//...
Break;
}

In this program fragment, only the value of variable A is taken out in the brackets of the switch at the beginning, and then the following case is compared one by one. The difference in efficiency is here. Of course, it is not good to use if. In case of composite conditions, the switch cannot help, because it cannot combine complex conditional statements in the switch, then you have to use if. Simply put, if and switch can be used flexibly together.

Top me

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.