Macro that compares variables

Hi, guys, I'm trying to build a macro that will compare a user specified amount of variables, like so:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>

//compares x to only a and b
#define equalTo(x, a, b) x != a && x != b 

int main()
{
	int x;

	do
	{
		std::cout << "x = ";
		std::cin >> x;
	} while (equalTo(x, 1, 2));  //I wanna input as many as i want to be compared to "x"
	//for example i want equalTo(x, 1, 2, 3, 4, 5) to work too, without a new macro
	
        std::cout << "x = " << x;

	std::cin.ignore();
	std::cin.get();
	return 0;
}
Last edited on
Why should I use inline functions instead of plain old #define macros?
https://isocpp.org/wiki/faq/inline-functions#inline-vs-macros

1
2
3
4
5
6
7
8
template < typename FIRST, typename SECOND >
constexpr bool equal_to( const FIRST& first, const SECOND& second )
{ return first == second ; }


template < typename FIRST, typename SECOND, typename... REST >
constexpr bool equal_to( const FIRST& first, const SECOND& second, const REST&... rest )
{ return equal_to( first, second ) && equal_to( second, rest... )  ; }

http://coliru.stacked-crooked.com/a/29d7d249046faf7c
Using a macro here is a mistake... too many things can go (horribly) wrong.

If you want to check that x is one of the arguments, you can use a variadic template function 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
#include <iostream>

template <typename T>
bool equalToAnyOf( T x0 )
{
  return false;
}

template <typename T, typename... Ts>
bool equalToAnyOf( T x0, T x1, Ts... xs )
{
  return (x0 == x1) ? true : equalToAnyOf( x0, xs... );
}

int main()
{
	int x;

	do
	{
		std::cout << "x? ";
		std::cin >> x;
	} 
        while (equalToAnyOf(x, 1, 2));
        
        std::cout << "x = " << x;

	std::cin.ignore();
	std::cin.get();
	return 0;
}

It seems like you are making a design mistake, though. What exactly are you planning to use this for?
I was just playing around with code. I had an "if" statement that compared a variable to 13 numbers. So it was a pain and I thought I'd figure out a way to make it shorter and look cooler. :P

Thank you all for your answers!
sasauke wrote:
I had an "if" statement that compared a variable to 13 numbers.
This sounds like a design defect. Consider using a container + loop instead.
Topic archived. No new replies allowed.