Error cannot appear in a constant-expression switch

error cannot appear in a constant-expression switch

en.wikibooks.org › wiki › GCC_Debugging › Errors › variable_cannot_ap. Why can I not use my constant in the switch - case statement in Objective-C? [error = Expression is not an integer constant expression] · Expression is not an. This error can occur when a character value described by a hex constant is too large to be represented in a char variable, for example: char x = '\x100';. 28.

What: Error cannot appear in a constant-expression switch

Error cannot appear in a constant-expression switch
Error cannot appear in a constant-expression switch
Error cannot appear in a constant-expression switch
IPHONE 4G ERROR 14
  1. #include <iostream>

  2. #include <string>

  3. usingnamespace std;

  4.  

  5. int main(){

  6. string s ="Test";

  7. // your code goes here

  8. switch(str2int(s))

  9. {

  10. case str2int("Test"):

  11. cout<<"YES"<< endl;

  12. break;

  13. case str2int("NotTest"):

  14. cout<<"NO"<< endl;

  15. break;

  16. default

  17. cout<<"ERROR"<< endl;

  18. break;

  19. }

  20. return0;

  21. }

I2luY2x1ZGUgPGlvc3RyZWFtPgojaW5jbHVkZSA8c3RyaW5nPgp1c2luZyBuYW1lc3BhY2Ugc3RkOwoKaW50IG1haW4oKSB7CglzdHJpbmcgcyA9ICJUZXN0IjsKCS8vIHlvdXIgY29kZSBnb2VzIGhlcmUKCXN3aXRjaCAoc3RyMmludChzKSkKCXsKICAJCWNhc2Ugc3RyMmludCgiVGVzdCIpOgogIAkJCWNvdXQgPDwgIllFUyIgPDwgZW5kbDsKICAgIAkJYnJlYWs7CiAgCQljYXNlIHN0cjJpbnQoIk5vdFRlc3QiKToKICAJCQljb3V0IDw8ICJOTyIgPDwgZW5kbDsKICAgIAkJYnJlYWs7CiAgICAJZGVmYXVsdAogICAgCQljb3V0IDw8ICJFUlJPUiIgPDwgZW5kbDsKICAgIAkJYnJlYWs7Cgl9CglyZXR1cm4gMDsKfQ==

Why Can I Not Use My Constant In The Switch Case Statement In Objective C Error Expression Is Not An Integer Constant Expression

Why can I not use my constant in the switch - case statement in Objective-C ? [error = Expression is not an integer constant expression]

Tags: tagsswitch-statementobjective-ccaseconstants Answers: 1

[Solved]-Switch error:: cannot appear in a constant-expression-C++

condition expression must be of integral type, or convertible to integral type, error smart 2.8.0 must be const.

6.4.2 [stmt.switch]

The condition shall be of integral type, enumeration type, or of a class type for which a single conversion function to integral or enumeration type exists (12.3). If the condition error cannot appear in a constant-expression switch of class type, error cannot appear in a constant-expression switch, the condition is converted by calling that conversion function, and the result of the conversion is used in place of the original condition for the remainder of this section. Integral promotions are performed. Any statement within the switch statement can be labeled with one or more case labels as follows:

case constant-expression :

where the constant-expression shall be an integral constant-expression. The integral constant-expression (5.19) is implicitly converted to the promoted type of the switch condition. No two audio - error mp3 download of the case constants in the same switch shall have the same value after conversion to the promoted type of the switch condition.

Your expression isn't a constant expression, error cannot appear in a constant-expression switch, even though the variable itself isso you can't switch on it. You'll need to use an .

You have another problem though:

You create a ,

.then you initialize the member of that union,

.and then you access the member of that union.

This evokes undefined behavior according to the standard. In the language of the Standard, 2 members of a union can't be active at one time. Meaning you can't treat a union like a caster.

constexpr specifier (since C++11)

[edit]Explanation

The specifier declares that it is possible to evaluate the value of the function or variable at compile time. Such variables and functions can then be used where only compile time constant expressions are allowed (provided that appropriate function arguments are given).

A specifier used in an object declaration or non-static member function(until C++14) implies. A specifier used in a function or static data member(since C++17) declaration implies. If any declaration of a function or function template has a specifier, then every declaration must contain that specifier.

A variable must satisfy the following requirements:

  • it must have constant destruction, i.e. either:
  • it is not of class type nor (possibly multi-dimensional) array thereof, or
  • it is of class type or (possibly multi-dimensional) array thereof, that class type has a constexpr destructor, and for a hypothetical expression e whose only effect is error cannot appear in a constant-expression switch destroy the object, e would be a core constant expression if the lifetime of the object and its non-mutable subobjects (but not its mutable subobjects) were considered to start within e.
(since C++20)

If a variable is not translation-unit-local, it should not be initialized to point to, or refer to, or have a (possibly recursive) subobject that points to or refers to, error cannot appear in a constant-expression switch translation-unit-local entity that is usable in constant expressions. Such initialization is disallowed in a module interface unit (outside its private-module-fragment, if any) or a module partition, and is deprecated in any other context.

(since C++20)

A function must satisfy the following requirements:

(until C++20)
  • its return type (if any) must be a LiteralType
  • each of its parameters must be a LiteralType
  • for constructor and destructor(since C++20), the class must have no virtual base classes
  • there exists at least one set of argument values such that an invocation of the function could be an evaluated subexpression of a core constant expression(for constructors, use in a constant initializer is sufficient)(since C++14). No diagnostic is required for a violation of this bullet.

A constructor whose function body is not =delete; must satisfy the following additional requirements:

  • for the constructor of a class or struct, error cannot appear in a constant-expression switch, every base class sub-object and every non-variant non-static data member must be initialized. If the class is a union-like class, for each of its non-empty anonymous union members, exactly one variant member must be initialized
  • for the constructor of a non-empty union, exactly one non-static data member must be initialized
(until C++20)
  • every constructor selected to initializing non-static data members and base class must be a constexpr constructor.

Destructors cannot bebut a trivial destructor can be implicitly called in constant expressions.

(until C++20)

A destructor whose function body is not =delete; must satisfy the following additional requirements:

  • every destructor used to destroy non-static data members and base class must be a constexpr destructor.
(since C++20)

For constexpr function templates and constexpr member functions of class templates, at least one specialization must satisfy the abovementioned requirements. Other specializations are still considered as constexpr, error cannot appear in a constant-expression switch, even though a call to such a function cannot appear in a constant expression.

[edit]Notes

Because the noexcept operator always returns for a constant expression, it can be used to check if a particular invocation of a constexpr function takes the constant expression branch:

constexprint f();constexprbool b1 =noexcept(f());// false, undefined constexpr functionconstexprint f(){return0;}constexprbool b2 =noexcept(f());// true, f() is a constant expression
(until C++17)

Constexpr constructors are permitted for classes that aren't literal types. For example, the default constructor of std::unique_ptr is constexpr, allowing constant initialization.

Reference variables can be declared constexpr (their initializers have to be reference constant expressions):

staticconstexprintconst& x =42;// constexpr reference to a const int object// (the object has static storage duration// due to life extension by a static reference)

Even though try blocks and inline assembly are allowed in constexpr functions, throwing exceptions or executing the assembly is still disallowed in a constant expression.

If a variable has constant destruction, there is no need to generate machine code in order to call destructor for it, even if its destructor is not trivial.

(since C++20)

[edit]Keywords

[edit]Example

Definition of a C++11 constexpr function which computes factorials and a literal type that extends string literals:

Run this code

#include <iostream>#include <stdexcept>   // C++11 constexpr functions use recursion rather than iteration// (C++14 constexpr functions may use local variables and loops)constexprint factorial(int n){return n <=1?1:(n * factorial(n -1));}   // literal classclass conststr {constchar* p;std::size_t sz;public:template<std::size_t N>constexpr conststr(constchar(&a)[N]): p(a), sz(N -1){}   // constexpr functions signal errors by throwing exceptions// in C++11, they must do so from the conditional operator ?:constexprchar operator[](std::size_t n)const{return n < sz ? p[n]:throwstd::out_of_range("");}   constexprstd::size_t size()const{return sz;}};   // C++11 constexpr functions had to put everything in a single return statement// (C++14 doesn't have that requirement)constexprstd::size_t countlower(conststr s, std::size_t n =0, std::size_t c =0){return n == s.size()? c :'a'<= s[n]&& s[n]<='z'? countlower(s, n +1, c +1): countlower(s, n +1, c);}   // output function that requires a compile-time constant, for testingtemplate<int n>struct constN { constN(){std::cout<< n <<'\n';}};   int main(){std::cout<<"4! = "; constN<factorial(4)> out1;// computed at compile time   volatileint k =8;// disallow optimization using volatilestd::cout<< k <<"! = "<< factorial(k)<<'\n';// computed at run time   std::cout<<"the number of lowercase letters in \"Hello, world!\" is "; constN<countlower("Hello, world!")> out2;// implicitly converted to error cannot appear in a constant-expression switch

4! = 24 8! = 40320 the number of lowercase letters in "Hello, world!" is 9

[edit]Defect reports

The following behavior-changing defect reports were applied retroactively to previously published C++ standards.

DR Applied to Behavior as published Correct behavior
CWG 1712 C++14 a constexpr variable template was required to have all
its declarations contain the constexpr specifier
(it is redundant because there cannot be more than one
declaration of a variable template with the constexpr specifier)
not required anymore
CWG 1911 Fatal error lnk1168 cannot open for writing constexpr constructors for non-literal types were not allowed allowed in constant initialization
CWG 2004 C++11 copy/move of a union with a mutable member
was allowed in a constant expression
mutable variants disqualify
implicit copy/move
CWG 2163 C++14 labels were allowed in constexpr functions
even though gotos are prohibited
labels also prohibited
CWG 2268 C++11 copy/move of a union with a ogasoda character generator error was prohibited by CWG issue 2004 allowed if the object is created
within the constant expression

[edit]See also

Switch error:: cannot appear in a constant-expression

condition expression must be of integral type, or convertible to integral type, and must be const.

6.4.2 [stmt.switch]

The condition shall be of integral type, enumeration type, or of a class type for which a single conversion function to integral or enumeration type exists 1046 mysql error. If the condition is of class type, the condition is converted by calling that conversion function, and the result of the conversion is used in place of the original condition for the remainder of this section. Integral promotions are performed. Any statement within the switch statement can be labeled with one or more case labels as follows:

case constant-expression :

where the constant-expression shall be an integral constant-expression. The integral constant-expression (5.19) is implicitly converted to the promoted type of the switch condition. No two error cannot appear in a constant-expression switch of the case constants in the same switch shall have the same value after conversion to the promoted type of the switch condition.

Your expression isn't a constant expression, even though the variable itself isso you can't switch on it. You'll need to use an .

You have another problem though:

You create a ,

.then you initialize the member of that union,

.and then you access the member of that union.

This evokes undefined behavior according to the standard. In the language of the Standard, 2 members of a union can't be active at one time. Meaning you can't treat a union like a caster.

answered Sep 29, 2010 at 16:01

user avatar
John DiblingJohn Dibling

97.7k2828 gold badges182182 silver badges313313 bronze badges

0 Comments

Leave a Comment