i need little help of urs in the above code, RightFrom Function is perfectly working but there is a logic bug in LeftFrom Function.
when i m sending North as argument the result from LeftFrom is -1 but i need 0. help me to solve this issue.

#include <iostream>
using namespace std;
enum direction{
	North,
	East,
	South,
	West,
};

direction RightFrom(direction d){
	return direction((d+1) % 4);
}

direction LeftFrom(direction d){
	return direction((d-1) % 4);
}

void main(){
	cout << RightFrom(West) << endl; // West = 4 and it will output 0 as required
	
	cout << LeftFrom(North) << endl; // North = 0 and it will output -1 ( but i need the result 0)	
}

Dani AI

Generated

The symptom is the modulo with a negative left operand: when d is 0, (d - 1) % 4 yields -1 in C++, so the enum value printed becomes a negative integer. See the C++ remainder rules for details: C++ remainder operator behavior. For this is not a logic bug in printing — it’s the math.

Two robust fixes that avoid the negative-remainder trap:

  • Convert the enum to its underlying integer type, make the operand non-negative before the %, then cast back. This is portable and clear:
#include <type_traits>

direction LeftFrom(direction d) {
    using UT = std::underlying_type_t<direction>;
    UT v = static_cast<UT>(d);
    v = (v + 4 - 1) % 4;   // ensure non-negative before modulo
    return static_cast<direction>(v);
}
  • Use a small lookup table. This is simple, fast, and avoids arithmetic surprises altogether:
#include <array>

constexpr std::array<direction, 4> left_of = { West, North, East, South };
static_assert(left_of.size() == 4, "direction count mismatch");

direction LeftFrom(direction d) {
    return left_of[static_cast<std::size_t>(d)];
}

Note: was pointing toward biasing the operand to avoid negativity; proposed an explicit underflow check. Both ideas are valid — the first is concise, the second is simple to read. For production code prefer the underlying-type + modulo or the lookup table and add a compile-time check (static_assert) so future enum changes won’t break the logic. Also remember that streaming an enum to cout prints its integer value; use static_cast<int>(...) or a name mapper if you need human-readable directions.

Recommended Answers

All 2 Replies

how about this: return (d-1) < 0 ? North : d-1; No need for the mod operator.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.