qed
qed

Reputation: 23104

c++ enum class not displayed correctly

Here is the code:

#include "stdafx.h"
#define _USE_MATH_DEFINES
#include <cmath>
#include <iostream>
#include <iomanip>


enum Suit : long {Heart, Club, Spade, Diamond};
enum class Color : char {Red = '*', Blue, Yellow, Green};
int main(int argc, wchar_t* argv[])
{
    using namespace std;
    auto suit = Suit::Club; 
    auto color = Color::Yellow;
    cout << setw(37) << left << "Suit value: " << setw(5) << right << suit << endl;
    cout << setw(37) << left << "Suit value +10: " << setw(5) << right << suit + 10 << endl;
    cout << setw(37) << left << "Color value: " << setw(5) << right << static_cast< char >(color) << endl;
    cout << setw(37) << left << "Color value +10: " << setw(5) << right << static_cast< int >(color) << endl;

    wchar_t x;
    wcin >> x;
    return 0;
}

Result running in vs2017:

Suit value:                              1
Suit value +10:                         11
Color value:                             ,
Color value +10:                        44

So the char * was printed as a comma, why?

Upvotes: 0

Views: 71

Answers (2)

Nespl NS3
Nespl NS3

Reputation: 52

Ascii Code Table

As you know how enum work, variable of enum get value +1 from last value. for Ex-

enum {
      sunday = 0, monday, tueday, ... , saturday 
}

if you acces the value of monday it will 1. as you have given red = '*'. so for complier your enum will look like this.

enum {
      red = '*',
      blue = '+',
      yellow = ','
} 

so now you know.

Upvotes: 0

CinCout
CinCout

Reputation: 9619

Red is '*', and Yellow is '*' + 2, which is ','.

More specifically, 42 is the ASCII value for '*', and 44 is for ',', and Red and Yellow differ by 2.

Upvotes: 3

Related Questions