3

Consider the following code:

#include<iostream>


enum week
{
    sun=1,
    mon,
    tue,
    wed,
    thr,
    fri,
    sat
};


week &operator++(week& day,int)
{
    if(day==sat)
        day=sun;
    else
        day++; // This expression
   return day;
}


int main()
{
    week day=sun;
    for(int i=0;i<=10;i++,day++)
    {
        std::cout<<day;
    }
}

In the expression day++ it goes into infinite recursion.

If I cast it like ((int)day)++ the compiler gives the following error:

      error: lvalue required as increment operand

If I change the line to day=week(((int)day)+1) it works. But how to fix the above code so it works with the ++ operator?

5
  • Why do you insist on ++ operator. What's wrong with day=week(((int)day)+1);? You can also write simply return day = week(((int)day%7)+1);. Commented Dec 16, 2019 at 14:28
  • I would ask for is there any option available for using ++ operator. Commented Dec 16, 2019 at 14:30
  • Unscoped enumerations are basically glorified symbolic integer constants. You might have better luck with stronger typed scoped enumerations. Commented Dec 16, 2019 at 14:32
  • I suggest not relying on self-modifying ++ as much. week next(week day) { if (day==sat) return sun; return week(((int)day)+1); and in the for loop, use day = next(day). Commented Dec 16, 2019 at 15:10
  • In addition to what everyone else said, your POST-increment operator is returning the wrong value anyway. POST-increment (day++) is supposed to return a copy of the previous value prior to incrementing. Your code is more suited for a PRE-increment (++day) operator instead, which returns a reference to the modified value. See Increment/decrement operators for more details Commented Dec 16, 2019 at 16:56

3 Answers 3

5

The default increment operator doesn't work well with enums. You'll have to overload the increment operator (with your week(((int)day)+1) logic) and handle the wrap-around in that overload function instead.

Sign up to request clarification or add additional context in comments.

Comments

4

One way round the compiler error is to cast to a reference instead

((int&)day)++;

but you should take care that the backing type of the enum is an int:

enum week : int
{
    // and so on

If that's not to your taste and would rather have the compiler decide the backing type for you then use

((std::underlying_type<week>::type&)day)++;

Comments

4

(int)day returns an int, which you try to increment by ++ operator. So basically you do something like ... = 5++ which is not legal.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.