Which is better, switch or if methods?

  • (2 Pages)
  • +
  • 1
  • 2

16 Replies - 553 Views - Last Post: 16 May 2019 - 04:14 AM Rate Topic: -----

#1 Ben_C   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 12
  • Joined: 25-May 18

Which is better, switch or if methods?

Posted 15 May 2019 - 07:50 AM

Hello all,

I'm currently attempting to teach myself C++, my first little programme is a simple counter with a login. I originally wrote it using an if statment. However I have just learnt about switches. I'm wondering what exactly is the difference between the two?

Here is my original code with an if:

#include <iostream>
#include <fstream>
#include <string>
#include <conio.h>
#include "countNumbers.cpp"

int login() {
	int choice;
	std::cout << "1: Register\n2: Login\n"; std::cin >> choice;

        if (choice == 1)
	{
		std::string userName, userPass;

		std::cout << "select a username: \n"; std::cin >> userName;
		std::cout << "select a password: \n"; std::cin >> userPass;
		
		std::ofstream file;
		file.open(".\\username.txt");

		file << userName << std::endl << userPass;
		file.close();
		return login();
	}
	else if (choice ==2)
	{

		bool status = isloggedIN();
		if (!status)
		{
			std::cout << '\a';
			std::cout << "Login failed, please try again!" << std::endl;
			getch();
			return 0;	
		}
		else
		{
			return countNumbers();
		}
	}
	
	return 0;
}


Here is the code with the switch method:
#include <iostream>
#include <fstream>
#include <string>
#include <conio.h>
#include "countNumbers.cpp"

int login() {
	int choice;
	std::string userName, userPass;
	std::ofstream file;
    bool isloggedIN();
	std::cout << "1: Register\n2: Login\n"; std::cin >> choice;

	switch (choice)	{
		case 1:
			std::cout << "select a username: \n"; std::cin >> userName;
			std::cout << "select a password: \n"; std::cin >> userPass;
		
			
			file.open(".\\username.txt");
			file << userName << std::endl << userPass;
			file.close();
			return login();

		break;
		

		case 2:
		
		bool status = isloggedIN();
		if (!status)
		{
			std::cout << '\a';
			std::cout << "Login failed, please try again!" << std::endl;
			getch();
			return 0;	
		}
		else
		{
			return countNumbers();
		}

	}
	return 0;
} 


for completeness the main.cpp code is here:
#include <iostream>
#include <fstream>
#include <string>
#include "login.cpp"

bool isloggedIN()
{
	std::string userName, userPass, uN, uP;
	std::cout << "select a username: \n"; std::cin >> userName;
	std::cout << "select a password: \n"; std::cin >> userPass;
	
	std::ifstream read(".\\username.txt");
	getline(read, uN);
	getline(read, uP); 

	if (uN == userName && uP == userPass)
	{
		return true;
	}
	else
	{
		return false;
	}
}

int main(){
	int login();
	int countNumbers();
	return login();	
}



Is This A Good Question/Topic? 0
  • +

Replies To: Which is better, switch or if methods?

#2 modi123_1   User is offline

  • Suitor #2
  • member icon



Reputation: 15069
  • View blog
  • Posts: 60,173
  • Joined: 12-June 08

Re: Which is better, switch or if methods?

Posted 15 May 2019 - 07:56 AM

Switches are super good ways to collapse a lot of if statements into one nice package for the compiler, and I believe are a little faster as they are predetermined versus stringing along a bunch of IFs.

It also helps to minimize missing 'ELSE' problems.. say in the top example where there is an IF, and ELSE IF, but no final else.
Was This Post Helpful? 1
  • +
  • -

#3 Ben_C   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 12
  • Joined: 25-May 18

Re: Which is better, switch or if methods?

Posted 15 May 2019 - 08:09 AM

I hadn't noticed the missing else, suppose I could just use else rather than else if, though having said that I've rewritten the script to use switch as it looks a lot neater.
Was This Post Helpful? 0
  • +
  • -

#4 modi123_1   User is offline

  • Suitor #2
  • member icon



Reputation: 15069
  • View blog
  • Posts: 60,173
  • Joined: 12-June 08

Re: Which is better, switch or if methods?

Posted 15 May 2019 - 08:19 AM

Quote

suppose I could just use else rather than else if,

So no response from the app if I input 3, -20, or "a"?
Was This Post Helpful? 0
  • +
  • -

#5 Ben_C   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 12
  • Joined: 25-May 18

Re: Which is better, switch or if methods?

Posted 15 May 2019 - 08:24 AM

Currently the programme terminates if any other input is given. I'd like to eventually look at possibly adding in a catch all for any other input, as well as encrypting the passwords and being able to create a database of more than one user at a time :).
Was This Post Helpful? 0
  • +
  • -

#6 Ben_C   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 12
  • Joined: 25-May 18

Re: Which is better, switch or if methods?

Posted 15 May 2019 - 08:48 AM

Apologies for the double post, but I can't seem to find where to edit my previous post, I have amended my code so that if the user inputs any other value other than 1 or 2 the programme terminates.

#include <iostream>
#include <fstream>
#include <string>
#include <conio.h>
#include "countNumbers.cpp"
#include "isloggedIN.cpp"

int login() {
	int choice;
	std::string userName, userPass;
	std::ofstream file;
    bool isloggedIN();
	std::cout << "1: Register\n2: Login\n"; std::cin >> choice;
	if ((choice != 1)&&(choice != 2))
	{
		std::cout << '\a';
		std::cout << "Choice not recognised programme will now terminate.";
		return 0;
	}
	else
	{
		switch (choice)	{
			case 1:
				std::cout << "select a username: \n"; std::cin >> userName;
				std::cout << "select a password: \n"; std::cin >> userPass;
				file.open(".\\username.txt");
				file << userName << std::endl << userPass;
				file.close();
				return login();
				
			break;
				
			case 2:
				bool status = isloggedIN();
				if (!status)
				{
					std::cout << '\a';
					std::cout << "Login failed, programme will now terminate!" << std::endl;
					getch();
					return 0;	
				}
				else
				{
					return countNumbers();
				}
			}	
		}
	return 0;
}

Was This Post Helpful? 0
  • +
  • -

#7 Skydiver   User is offline

  • Code herder
  • member icon

Reputation: 6918
  • View blog
  • Posts: 23,523
  • Joined: 05-May 12

Re: Which is better, switch or if methods?

Posted 15 May 2019 - 08:51 AM

Are you sure you want to recursively call yourself on line 29?

What is the point of the if statement? Why now simply have a default case in the switch statement to deal with unmatched inputs?
Was This Post Helpful? 0
  • +
  • -

#8 modi123_1   User is offline

  • Suitor #2
  • member icon



Reputation: 15069
  • View blog
  • Posts: 60,173
  • Joined: 12-June 08

Re: Which is better, switch or if methods?

Posted 15 May 2019 - 08:52 AM

Fun nugget - switch statements have a 'default' bucket to tell it what to do if the entered value doesn't match any of the switch options. Seems that would negate the need for the IF in line 14.
Was This Post Helpful? 0
  • +
  • -

#9 Ben_C   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 12
  • Joined: 25-May 18

Re: Which is better, switch or if methods?

Posted 15 May 2019 - 08:58 AM

View PostSkydiver, on 15 May 2019 - 08:51 AM, said:

Are you sure you want to recursively call yourself on line 29?

What is the point of the if statement? Why now simply have a default case in the switch statement to deal with unmatched inputs?


It was recursive to allow the user to register and then login if needed. Would
return main();
be a better option?
Was This Post Helpful? 0
  • +
  • -

#10 jon.kiparsky   User is offline

  • Beginner
  • member icon


Reputation: 11543
  • View blog
  • Posts: 19,632
  • Joined: 19-March 11

Re: Which is better, switch or if methods?

Posted 15 May 2019 - 09:15 AM

In my view, a switch is useful if the following hold:
- your language does not support object-oriented programming or dictionary lookups (ie, you're writing straight C) or
- you have benchmarked an object-oriented solution or dictionary lookup and found it to be a critical time-sink


I don't know how switches are implemented in C or C++, but this post discusses how they work in Java, which might give you some tools for thought. My guess is that something similar is happening in your C and C++ code as well.


From a code quality perspective, I would strongly suggest you minimize the content of the switch as much as possible. Rather than expressing the desired behavior in the case blocks, I would call a function. The benefit of this is that the reader will be able to see well-chosen function names rather than having to parse your code to understand what each case leads to. Something like this:

		switch (choice)	{
			case 1:
				doLogin();
				break;
				
			case 2:
				showCountNumbers();
				break;
			}	
		}

Was This Post Helpful? 0
  • +
  • -

#11 Ben_C   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 12
  • Joined: 25-May 18

Re: Which is better, switch or if methods?

Posted 15 May 2019 - 09:42 AM

Thanks for the feed back, I'll take a look at the link you provided when I get home. I have updated the code to remove the actual task from the switch it does make the code look a lot better.

#include <iostream>
#include <fstream>
#include <string>
#include <conio.h>
#include "countNumbers.cpp"
#include "isloggedIN.cpp"

int def(){
	std::cout << '\a';
	std::cout << "Choice not recognised programme will now terminate.";
	return 0;
}

int checkLogin(){
	std::string userName, userPass;
	std::ofstream file;
	std::cout << "select a username: \n"; std::cin >> userName;
	std::cout << "select a password: \n"; std::cin >> userPass;
	file.open(".\\username.txt");
	file << userName << std::endl << userPass;
	file.close();
	return 0;
}
int loginFailed(){
	bool status = isloggedIN();
		if (!status)
		{
			std::cout << '\a';
			std::cout << "Login failed, programme will now terminate!" << std::endl;
			getch();
			return 0;	
		}
		else
		{
			return countNumbers();
		}
}

int login() {
	int choice;
	bool isloggedIN();
	std::cout << "1: Register\n2: Login\n"; std::cin >> choice;
	switch (choice)	{
		default:
			def();
		break;
		case 1:
			checkLogin();
		break;
		case 2:
			loginFailed();
		}	
	return 0;
}

This post has been edited by Skydiver: 15 May 2019 - 10:21 AM
Reason for edit:: Removed unnecessary quote. No need to quote the post above yours.

Was This Post Helpful? 0
  • +
  • -

#12 Skydiver   User is offline

  • Code herder
  • member icon

Reputation: 6918
  • View blog
  • Posts: 23,523
  • Joined: 05-May 12

Re: Which is better, switch or if methods?

Posted 15 May 2019 - 10:28 AM

Ben_C: There is no need to quote the post above yours. Just use the big Reply button or the Fast Reply area. If you must quote, try to trim down to the specific item you want to address.

Calling main() is actually against the C and C++ standard. Do not do this. main() is supposed to be only the entry point to your program from the OS.

If you need to loop back to do an operation one or more times, use a loop. Use a while or do-while loop.
Was This Post Helpful? 0
  • +
  • -

#13 jimblumberg   User is offline

  • member icon

Reputation: 5732
  • View blog
  • Posts: 17,558
  • Joined: 25-December 09

Re: Which is better, switch or if methods?

Posted 15 May 2019 - 10:51 AM

View PostBen_C, on 15 May 2019 - 10:58 AM, said:

It was recursive to allow the user to register and then login if needed. Would
return main();
be a better option?


No it is never acceptable to call main(), just return to the calling function.

Also recursive calls are usually not the best way to handle things like this, just use one of the basic loop mechanisms.

Lastly picking between switch and if()/else if() is really just about "style". Many people prefer if/else if() over switch() because a switch is only designed for a single value while the if() method allows ranges to be selected. With today's compilers the difference in machine code is really minimal in most cases and in some cases the code may be identical.

And lastly, for now, when speaking about "style" it is considered a bad practice in C++ and modern C to declare your variables in one big clump at the beginning of some scope. It is better to declare variables close to first use and in as limited scope as possible.


Jim
Was This Post Helpful? 1
  • +
  • -

#14 jon.kiparsky   User is offline

  • Beginner
  • member icon


Reputation: 11543
  • View blog
  • Posts: 19,632
  • Joined: 19-March 11

Re: Which is better, switch or if methods?

Posted 15 May 2019 - 11:11 AM

View Postjimblumberg, on 15 May 2019 - 12:51 PM, said:

With today's compilers the difference in machine code is really minimal in most cases and in some cases the code may be identical.


This is interesting to me. Do you think you could whip up an example where an if chain and a switch produce identical code?

I'm curious to see what code would be generated - as you can see in the Java example, there are some pretty distinctive compile products for switch statements, so I'd like to see whether how C[++] handles it.
Was This Post Helpful? 0
  • +
  • -

#15 Skydiver   User is offline

  • Code herder
  • member icon

Reputation: 6918
  • View blog
  • Posts: 23,523
  • Joined: 05-May 12

Re: Which is better, switch or if methods?

Posted 15 May 2019 - 02:12 PM

You may find the following blogpost interesting: switches and jump tables . This is specific to the Microsoft compiler though. Almost every other compiler will have different implementations.
Was This Post Helpful? 1
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2