Студопедия — Constant expressions
Студопедия Главная Случайная страница Обратная связь

Разделы: Автомобили Астрономия Биология География Дом и сад Другие языки Другое Информатика История Культура Литература Логика Математика Медицина Металлургия Механика Образование Охрана труда Педагогика Политика Право Психология Религия Риторика Социология Спорт Строительство Технология Туризм Физика Философия Финансы Химия Черчение Экология Экономика Электроника

Constant expressions






A constant-expression is an expression that can be fully evaluated at compile-time.

constant-expression:
expression

A constant expression must be the null literal or a value with one of the following types: sbyte, byte, short, ushort, int, uint, long, ulong, char, float, double, decimal, bool, object, string, or any enumeration type. Only the following constructs are permitted in constant expressions:

· Literals (including the null literal).

· References to const members of class and struct types.

· References to members of enumeration types.

· References to const parameters or local variables

· Parenthesized sub-expressions, which are themselves constant expressions.

· Cast expressions, provided the target type is one of the types listed above.

· checked and unchecked expressions

· Default value expressions

· The predefined +, –,!, and ~ unary operators.

· The predefined +, –, *, /, %, <<, >>, &, |, ^, &&, ||, ==,!=, <, >, <=, and >= binary operators, provided each operand is of a type listed above.

· The?: conditional operator.

The following conversions are permitted in constant expressions:

· Identity conversions

· Numeric conversions

· Enumeration conversions

· Constant expression conversions

· Implicit and explicit reference conversions, provided that the source of the conversions is a constant expression that evaluates to the null value.

Other conversions including boxing, unboxing and implicit reference conversions of non-null values are not permitted in constant expressions. For example:

class C {
const object i = 5; // error: boxing conversion not permitted
const object str = “hello”; // error: implicit reference conversion
}

the initialization of iis an error because a boxing conversion is required. The initialization of str is an error because an implicit reference conversion from a non-null value is required.

Whenever an expression fulfills the requirements listed above, the expression is evaluated at compile-time. This is true even if the expression is a sub-expression of a larger expression that contains non-constant constructs.

The compile-time evaluation of constant expressions uses the same rules as run-time evaluation of non-constant expressions, except that where run-time evaluation would have thrown an exception, compile-time evaluation causes a compile-time error to occur.

Unless a constant expression is explicitly placed in an unchecked context, overflows that occur in integral-type arithmetic operations and conversions during the compile-time evaluation of the expression always cause compile-time errors (§7.19).

Constant expressions occur in the contexts listed below. In these contexts, a compile-time error occurs if an expression cannot be fully evaluated at compile-time.

· Constant declarations (§10.4).

· Enumeration member declarations (§14.3).

· Default arguments of formal parameter lists (§10.6.1)

· case labels of a switch statement (§8.7.2).

· goto case statements (§8.9.3).

· Dimension lengths in an array creation expression (§7.6.10.4) that includes an initializer.

· Attributes (§17).

An implicit constant expression conversion (§6.1.9) permits a constant expression of type int to be converted to sbyte, byte, short, ushort, uint, or ulong, provided the value of the constant expression is within the range of the destination type.







Дата добавления: 2015-09-07; просмотров: 516. Нарушение авторских прав; Мы поможем в написании вашей работы!



Обзор компонентов Multisim Компоненты – это основа любой схемы, это все элементы, из которых она состоит. Multisim оперирует с двумя категориями...

Композиция из абстрактных геометрических фигур Данная композиция состоит из линий, штриховки, абстрактных геометрических форм...

Важнейшие способы обработки и анализа рядов динамики Не во всех случаях эмпирические данные рядов динамики позволяют определить тенденцию изменения явления во времени...

ТЕОРЕТИЧЕСКАЯ МЕХАНИКА Статика является частью теоретической механики, изучающей условия, при ко­торых тело находится под действием заданной системы сил...

Решение Постоянные издержки (FC) не зависят от изменения объёма производства, существуют постоянно...

ТРАНСПОРТНАЯ ИММОБИЛИЗАЦИЯ   Под транспортной иммобилизацией понимают мероприятия, направленные на обеспечение покоя в поврежденном участке тела и близлежащих к нему суставах на период перевозки пострадавшего в лечебное учреждение...

Кишечный шов (Ламбера, Альберта, Шмидена, Матешука) Кишечный шов– это способ соединения кишечной стенки. В основе кишечного шва лежит принцип футлярного строения кишечной стенки...

Основные структурные физиотерапевтические подразделения Физиотерапевтическое подразделение является одним из структурных подразделений лечебно-профилактического учреждения, которое предназначено для оказания физиотерапевтической помощи...

Почему важны муниципальные выборы? Туристическая фирма оставляет за собой право, в случае причин непреодолимого характера, вносить некоторые изменения в программу тура без уменьшения общего объема и качества услуг, в том числе предоставлять замену отеля на равнозначный...

Тема 2: Анатомо-топографическое строение полостей зубов верхней и нижней челюстей. Полость зуба — это сложная система разветвлений, имеющая разнообразную конфигурацию...

Studopedia.info - Студопедия - 2014-2024 год . (0.013 сек.) русская версия | украинская версия