title | description | ms.date | ms.topic | f1_keywords | helpviewer_keywords | |||
---|---|---|---|---|---|---|---|---|
literal (C++/CLI) | The literal keyword is a Microsoft C++/CLI context-sensitive keyword for a compile-time constant. | 10/20/2020 | reference |
|
|
A variable (data member) marked as literal
in a /clr
compilation is a compile-time constant. It's the native equivalent of a C# const
variable.
(There are no remarks for this language feature that apply to all runtimes.)
(There are no remarks for this language feature that apply to only the Windows Runtime.)
A data member marked as literal
must be initialized when declared. And, the value must be a constant integral, enum, or string type. Conversion from the type of the initialization expression to the type of the literal
data member can't require a user-defined conversion.
No memory is allocated for the literal
field at runtime; the compiler only inserts its value in the metadata for the class. The literal
value is treated as a compile-time constant. The closest equivalent in Standard C++ is constexpr
, but a data member can't be constexpr
in C++/CLI.
A variable marked as literal
differs from one marked static const
. A static const
data member isn't made available in metadata to other compilers. For more information, see static
and const
.
literal
is a context-sensitive keyword. For more information, see Context-sensitive keywords.
This example shows that a literal
variable implies static
.
// mcppv2_literal.cpp// compile with: /clr ref structX { literal int i = 4; }; intmain() { int value = X::i; }
The following sample shows the effect of literal
in metadata:
// mcppv2_literal2.cpp// compile with: /clr /LD public ref structA { literal int lit = 0; staticconstint sc = 1; };
Notice the difference in the metadata for sc
and lit
: the modopt
directive is applied to sc
, meaning it can be ignored by other compilers.
.field public static int32 modopt([mscorlib]System.Runtime.CompilerServices.IsConst) sc = int32(0x00000001)
.field public static literal int32 lit = int32(0x00000000)
The following sample, authored in C#, references the metadata created in the previous sample and shows the effect of literal
and static const
variables:
// mcppv2_literal3.cs// compile with: /reference:mcppv2_literal2.dll// A C# programclassB{publicstaticvoidMain(){// OKSystem.Console.WriteLine(A.lit);System.Console.WriteLine(A.sc);// C# does not enforce C++ constA.sc=9;System.Console.WriteLine(A.sc);// C# enforces const for a literalA.lit=9;// CS0131// you can assign a C++ literal variable to a C# const variableconstinti=A.lit;System.Console.WriteLine(i);// but you cannot assign a C++ static const variable// to a C# const variableconstintj=A.sc;// CS0133System.Console.WriteLine(j);}}
Compiler option: /clr