why it throws an exception?

I have two problems, first, it throws an exception even i don't use double as argument, the second visual studio gives me this error(((C6287 Redundant code: the left and right sub-expressions are identical.)))

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
  #include<iostream>
#include<typeinfo>

int addValues(int a, int b)
{
	int sum;
	if (typeid(a).name() == "int" && typeid(b).name() == "int")
	{
		sum = a + b;
		std::cout << sum << std::endl;
	}
	else {
		throw - 1;
	}
	return 0;
}

int main()
{
	int num1, num2;
	std::cin >> num1 >> num2;

	try
	{
		addValues(num1, num2);

	}

	catch (int)
	{
		std::cout << "both of values must be integer" << std::endl;
		
	}

}
Last edited on
The exact result of typid(variable).name() is implementation-defined, and should not be used for portable, robust comparisons.
https://en.cppreference.com/w/cpp/types/type_info/name

Second, name() is a const char*, therefore overloading == operator doesn't work here. You're only comparison addresses.

Furthermore, C++ is already statically typed, so checking if an int is useless. It's always an int.

You're trying to prevent the user from typing in things like "asdf" into num1 and num2, right?
Or are you trying to prevent the user from typing in "3.4"? Or both?
Last edited on
GCC says:
 In function 'int addValues(int, int)':
7:26: warning: comparison with string literal results in unspecified behaviour [-Waddress]
7:55: warning: comparison with string literal results in unspecified behaviour [-Waddress]

In other words, syntax on line 7 is wrong.


That aside, num1, num2, a, and b are all int. Period. They cannot be anything else.

If the stream does not have two integers, then the input on line 21 will fail:
* The std::cin will have fail flag set
* Value of num1 and num2 is something, but still int

This is not the way to find out what the stream has.
4
5
6
7
8
9
10
11
12
13
14
15
16
int addValues(int a, int b)
{
	if (typeid(a).name() == typeid(int).name() && typeid(b).name() == typeid(int).name())
	{
		int sum = a + b;
		std::cout << sum << std::endl;
	}
	else
	{
		throw - 1;
	}
	return 0;
}

No thrown exception now. MSVC still gives the warning about redundant code, the if check works as expected:
3 5
8

Change either (or both) of the parameter types to a different POD type like long long or double and the if check fails because a long long/double is a different type than int.

What are you trying to do? It certainly is not a valid test to check if the user entered two integers.
a b
-858993460
Topic archived. No new replies allowed.