c++ - How does switch-case handle the value of the constant in a "case"? -



c++ - How does switch-case handle the value of the constant in a "case"? -

this question has reply here:

what mean (byte)-1 2 answers

let's have

typedef unsigned char byte; #define cputype_invalid ((byte)-1)

which case switch statement hit?

byte m_cputype; m_cputype = 0xff; switch (m_cputype) { case 255: cout << "hit 1"; case -1: cout << "hit 2"; case cputype_invalid: cout << "hit 3"; break; default: cout << "no hit"; break; }

what outcome then? , please elaborate.

warning

your code potentially ill-formed, , if dealing platform unsigned char consists of 8 bits (which case), is.

what standard say?

it's stated in standard 2 case constants shall not have same value after conversion integral type used switch-condition.

6.4.2p2 the switch statement [stmt.switch]

the status shall of intergral type, enumeration type, or class type. if of class type, status contextually implicitly converted (clause 4) integral or enumeration type. integral promotions performed. statement within switch statement can labeled 1 or more case labels follows:

case constant-expression :

where teh constant-expression shall converted constant look (5.19) of promoted type of switch condition. no 2 of case constants in same switch shall have same value after conversion promoted type of switch condition.

this means if integral type yield integral promotion type of m_cputype, treats static_cast<int> ((byte)-1) , static_cast<int> (255) beingness same value.. snippet ill-formed.

so, safe?

integral promotion method of integral type promoted type,if necessary easy implementation , logic when dealing 2 integral values potentially of different types.

4.5 integral promotions [conv.prom]

a prvalue of integer type other bool, char16_t, char32_t, or wchar_t integer conversion rank (4.13) less rank of int can converted prvalue of type int if int can represent values of source type; otherwise, source prvalue can converted prvalue of type unsigned int.

it's stated in standard unsigned char has less rank int, , type of switch status int, farther means; static_cast<int> (-1) != static_cast<int> (255).

but, on platforms maximum value of unsigned char 255 means (byte)-1) yield unsigned char value of 255. means 255 == cputype_invalid.

switch (m_cputype) { case 255: // (a) cout<<"hit 1"; case -1: cout<<"hit 2"; case cputype_invalid: // (b), same value (a) cout<<"hit 3"; break; default: cout<<"no hit"; break; }

you have 2 case constants after conversions yields same value: code ill-formed.

c++ switch-statement

Comments

Popular posts from this blog

model view controller - MVC Rails Planning -

ruby on rails - Devise Logout Error in RoR -

html - Submenu setup with jquery and effect 'fold' -