Calling function in switch case help

closed account (3RMzT05o)
My program: It is a very basic calculator. you have to enter 2 numbers and then either type "a" for adding and "m" for minus.

Problem: I have encountered some problem with call function when using "switch case". my function(add , minu) works very good outside switch case. however, when compiling, an error message inside the switch saying : " expression is not an integral constant expression."

Another problem: I realize the data type "string" doesn't exist in C++, what is the replacement for that?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
 #include <iostream>
using namespace std;

int add(int n1, int n2);
int minu(int n1, int n2);

int n1;
int n2;
int ans;
char work;

int main()
{
    cout << " Please enter a number:";
    cin >> n1 ;
    cout << " Please enter a number:";
    cin >> n2 ;
    cout << " What do you want to do? ";
    cin >> work;
    cout << work <<" Selected \n ";
    cout << add(n1, n2) << endl;
    cout << minu(n1, n2) << endl;
    switch(work)
    {
        case"a":
            cout << add(n1, n2);
            break; 
       case"m":
           cout << minu(n1, n2);
           break;
        default:
            cout << "Error";
   }
    
    
    return 0;
}

int add(int n1, int n2)
{
    ans = n1 + n2;
    return ans;
}

int minu(int n1, int n2)
{
    ans = n1 - n2;
    return ans;
} Put the code you need help with here.
Last edited on
just add #include <string> and you can use std::string or just string if you're already using the std namespace.

I believe switch is only for int , enums (which are usually ints), and char, which can be represented as int. Your cases have double quotes, so the compiler thinks you're trying to use strings instead of characters (single quotes).

If you wanted to use strings everywhere, you could make work a string, cin to work, and do regular if...else if...else if...else .
closed account (3RMzT05o)
Oh ,thank you, I can use string now, however I still can't call the function inside the switch.
Hello Garm,

As ick1 said I believe switch is only for int , enums (which are usually ints), and char, which can be represented as int. This is true, the problem in in the case statements. Since "work" is defined as a char you need to use a "char" in the case statements. I would also consider writing the case statements this way:
1
2
3
4
5
6
7
8
9
10
switch (work)
{
        case 'A':
        case 'a':
            cout << add(n1, n2);
            break;
       case 'M': 
       case 'm':
           cout << minu(n1, n2);
           break;

Notice the space between the word "case" and the choice and the single quotes to use a char instead of a string.

Accounting for both lower case and upper case is your responsibility not the users. Another alternative is to include the header file <cctype> and after line 19 add the line work=std::toupper(work); or use tolower your choice.

Lines 21 and 22 are not needed here unless they are for testing as they are done in the case statements.

Something to consider in your functions you could just say: return n1 + n2;.

Hope that helps,

Andy
Hello Garm,

I played with the program a bit. See what you think. I added a blank line or two and be sure to notice the comments in the program:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#include <iostream>
#include <limits>

//using namespace std;  // <--- Best not to use.

int add(int n1, int n2);
int minu(int n1, int n2);

// <--- Best not to use global variables.

int main()
{
	//  These are only used inside main and passed to the functions. Therefor they do not need to be global.
	int n1{};  // ALWAUS initialize your variables.
	int n2{};
	int ans{};
	char work{};

	std::cout << "\n Please enter a number: ";
	std::cin >> n1;
	std::cout << " Please enter a number: ";
	std::cin >> n2;
	std::cout << "\n What do you want to do? (A)dd/(M)inus: ";
	std::cin >> work;
	//work = std::toupper(work)  // <--- Requires header file <cctype>. An alternative to checking for each case.
	std::cout << (work == 'a' || work == 'A' ? "\n Add " : "\n Subtraction ") << " Selected \n " << std::endl;

	//std::cout << add(n1, n2) << std::endl;   // <--- Not needed unless for debugging.
	//std::cout << minu(n1, n2) << std::endl;  // <--- Not needed unless for debugging.

	switch (work)
	{
		case 'A':
		case 'a':
			std::cout << ' ' << n1 << " + " << n2 << " = " << add(n1, n2) << std::endl;
			break;
		case 'M':
		case 'm':
			std::cout << ' ' << n1 << " - " << n2 << " = " << minu(n1, n2) << std::endl;
			break;
		default:
			std::cout << "Error";
	}


	std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');  // <--- Requires header file <limits>.
	std::cout << "\n\n Press Enter to continue";
	std::cin.get();

	return 0;
}

int add(int n1, int n2)
{
	//ans = n1 + n2;
	//return ans;

	// <--- As an example.
	return n1 + n2;
}

int minu(int n1, int n2)
{
	ans = n1 - n2;
	return ans;
}


Give it a run and see what you think. You will notice how the output has changed.

Hope that helps,

Andy
closed account (3RMzT05o)
Wow, it really helped me, but would you mind explaning why "using spacename std;" isn't recommended? I can type alot fewer things if I type this at the beginning.

And what does this line mean:
std::cout << (work == 'a' || work == 'A' ? "\n Add " : "\n Subtraction ") << " Selected \n " << std::endl;
Last edited on
Hello Garm,

This is generally a copy and paste I use:
Try to avoid using using namespace std; in your programs it may seem easy now, but WILL get you in trouble some day.

It is better to learn to qualify what is in the standard name space with "std::" and then to learn what is in the standard name space now while it is easy. And not all at once to try to keep a job.

What you are most likely to use for now is "std::cout", "std::cin" and "std::endl". About a week or so of typing this and you will not even notice that you are doing it.

I would add to that someday you will create a variable or function using a name that you think is good, but turns out to also be in the standard name space. Then, when you compile the program, you will have a hard time with the error message which boils down to which are you trying to use the variable or function name that you created or the one in the standard name space which is different from what you want? Except for the name being the same?

The other possibility is, if you intend this to be a career, yours future employers are likely to tell you the line using namespace std; is not to be used in any of their programs. Now you will have to learn everything that is in the name space standard at one time when you should have been learning it slowly from the start.

I do not understand why schools feel that teaching you to use using namespace std; is a good thing. There are times that the "using" statement is useful and it is generally better to limit the scope of the "using" statement.

This is a link I give to people who thing that using namespace std; in a header file is OK, but actually that is worse: http://www.lonecpluspluscoder.com/2012/09/22/i-dont-want-to-see-another-using-namespace-xxx-in-a-header-file-ever-again/ It does not really apply here, but worth reading.

Hope that helped more than confused you,

Andy
closed account (3RMzT05o)
Thank you for pointing that out before it is too late
closed account (E0p9LyTq)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// why using namespace std is bad

#include <iostream>
#include <algorithm>

using namespace std;

unsigned int count; // global variables are also chock full of potential problems

int main()
{
   count++; // conflicts with std::count() in <algorithm>

   std::cout << count << '\n';
}

Visual Studio and Code::Blocks "chokes on the variable count when using namespace std;, it won't compile. Comment out or remove the line and it compiles.

A trivial example, but it shows why using namespace std; can cause problems that should not be problems.
closed account (3RMzT05o)
Oh, 1 word/function carrying the two meanings, so the computer doesn't know which meaning to use.
Last edited on
closed account (3RMzT05o)
Btw, how and where to know what to be #include? There are thousands of stuffs that can be #include . How do you know it is right for you. And why the computer can immediately load the #include stuff? Doesn't it need to download it from the internet ? And is the thing after #include called library?
Last edited on
No, they are not called "libraries". They are called "header files". They provide the information needed to use things from the C++ standard library. The header files are stored on your disk as part of the compiler installation. You know which ones to use by studying the language and learning about them. There are around 70 standard header files in C++. Other libraries will come with there own header files.
How and where to know what to #include?

Speaking of the standard library:
The language standard defines the components which must be present in certain files. You have to include at least one file which is required to contain the component you want. This has to happen before you first use the component.

For any given component, you can find out which header file you need by looking at a reference site like this one. My favorite reference site is cppreference.com:
http://en.cppreference.com/w/
although I know the stdlib pretty well at this point, so I don't usually need to look for that information any-more.

And why the computer can immediately load the #include stuff?

The standard library headers are already on your computer; they're distributed with your compiler. But if that the code you're including has been written by a third-party, yes, you'd have to download it and tell your compiler about it first.

Is the thing after #include called library?

Strictly speaking, the name after #include names a header file. You could probably call it a library, but that's a colloquialism at best and completely wrong at worst. It depends on context.
closed account (3RMzT05o)
Ok, thank you guys
Hello Garm,

Sorry I lost track when I had to restart my computer, It was running very slow at the time.

The line std::cout << (work == 'a' || work == 'A' ? "\n Add " : "\n Subtraction ") << " Selected \n " << std::endl; is basically a short form of an if statement.

The start work == 'a' || work == 'A' would be what you would find in if (work == 'a' || work == 'A'). The '?' is the then part and the ':' is the else part.

So it would if you typed in 'a' or 'A' then print "Add" to the screen else print "subtraction" to the screen. This is just one example of the ternary operator. See http://www.cplusplus.com/doc/tutorial/operators/#conditional for more information.

I may have copied an old version of what I said about the "using namespace". In the beginning you are most likely to use "std::" in front of "cin", "cout", "endl" and "string". As you learn you will find "std::size_t" is useful. "size_t" is just another name for "unsigned int" and the may be one of a few names where "std::" is optional.

A good IDE like Visual Studio or Code::blocks will help with learning what is in the standard name space. Also reading the posts here helps when you look at the code from those who have been around awhile. I do know in VS when you type "std::" a drop down box appears which shows what is in the standard namespace and I would say 1/2 or more comes from the header files that are included.

Hope that helps,

Andy
As you learn you will find "std::size_t" is useful. "size_t" is just another name for "unsigned int" and the may be one of a few names where "std::" is optional.


The size_t is not necessarily another name for an unsigned int. It is a implementation defined unsigned type usually either an unsigned int or an unsigned long, however it could be an unsigned short (unlikely) or a unsigned long long (perhaps in the future).

Also this "type" has it's roots in C which is probably the reason you don't always need to specify the namespace.

@FurryGuy, I'm really not seeing your point there. You just made a case against lowercase globals more than anything else, which is asking for trouble since we know all the std stuff is lowercase on purpose...

This lowercase globals issue should really be the thing to focus on -- for instance, we should be discouraging the OP from naming his methods like "add", instead naming "Add" or so. It's all these leftover bad C habits that have a ton of lowercase global (not namespaced) methods and vars that cause issues down the road. Classic culprits are custom "min" and "max" definitions scattered everywhere.
Last edited on
closed account (3RMzT05o)
Oh I get it, it is a good way to make code more simple.
Topic archived. No new replies allowed.