- if-else (Справочник по C#) if-else (C# Reference)
- Пример Example
- Пример Example
- Пример Example
- Спецификация языка C# C# language specification
- директивы #if, #elif, #else и #endif (C/C++) #if, #elif, #else, and #endif directives (C/C++)
- Грамматика Grammar
- Комментарии Remarks
- Операторы препроцессора Preprocessor operators
- defined defined
- __has_include __has_include
if-else (Справочник по C#) if-else (C# Reference)
Оператор if определяет, какой оператор будет выполняться при выполнения условия, заданного логическим выражением. An if statement identifies which statement to run based on the value of a Boolean expression. В приведенном ниже примере переменной bool типа condition присваивается значение true , а затем она проверяется оператором if . In the following example, the bool variable condition is set to true and then checked in the if statement. В результате получается The variable is set to true. . The output is The variable is set to true. .
Примеры в этом разделе можно выполнить, разместив их в методе Main консольного приложения. You can run the examples in this topic by placing them in the Main method of a console app.
Оператор if в С# может иметь две формы, как показано в приведенном ниже примере. An if statement in C# can take two forms, as the following example shows.
В операторе if-else , если condition имеет значение true, выполняется then-statement . In an if-else statement, if condition evaluates to true, the then-statement runs. Если condition имеет значение false, выполняется else-statement . If condition is false, the else-statement runs. Так как condition не может одновременно иметь значения true и false, then-statement и else-statement оператора if-else не могут выполняться оба. Because condition can’t be simultaneously true and false, the then-statement and the else-statement of an if-else statement can never both run. После выполнения then-statement или else-statement управление передается следующему оператору после оператора if . After the then-statement or the else-statement runs, control is transferred to the next statement after the if statement.
В операторе if , не включающем оператор else , если condition имеет значение true, выполняется then-statement . In an if statement that doesn’t include an else statement, if condition is true, the then-statement runs. Если condition имеет значение false, то управление передается следующему оператору после оператора if . If condition is false, control is transferred to the next statement after the if statement.
then-statement и else-statement могут состоять из одного или нескольких операторов, заключенных в фигурные скобки ( <> ). Both the then-statement and the else-statement can consist of a single statement or multiple statements that are enclosed in braces ( <> ). Для одного оператора скобки необязательны, но рекомендуются. For a single statement, the braces are optional but recommended.
Оператор или операторы в then-statement и else-statement могут быть любого типа, включая другой оператор if , вложенный в исходный оператор if . The statement or statements in the then-statement and the else-statement can be of any kind, including another if statement nested inside the original if statement. Во вложенных операторах if каждое предложение else относится к последнему оператору if , у которого нет соответствующего объекта else . In nested if statements, each else clause belongs to the last if that doesn’t have a corresponding else . В приведенном ниже примере Result1 получается, если оба выражения m > 10 и n > 20 имеют значение true. In the following example, Result1 appears if both m > 10 and n > 20 evaluate to true. Если m > 10 имеет значение true, но n > 20 — значение false, то получается Result2 . If m > 10 is true but n > 20 is false, Result2 appears.
Если вместо этого нужно, чтобы Result2 получался, когда значение (m > 10) равно false, можно указать такую связь с помощью фигурных скобок для задания начала и конца вложенного оператора if , как показано в приведенном ниже примере. If, instead, you want Result2 to appear when (m > 10) is false, you can specify that association by using braces to establish the start and end of the nested if statement, as the following example shows.
Result2 получается, если условие (m > 10) имеет значение false. Result2 appears if the condition (m > 10) evaluates to false.
Пример Example
В приведенном ниже примере вы вводите символ с помощью клавиатуры, а программа использует вложенный оператор if для определения того, является ли введенный символ буквой. In the following example, you enter a character from the keyboard, and the program uses a nested if statement to determine whether the input character is an alphabetic character. Если введенный символ является буквой, программа определяет его регистр. If the input character is an alphabetic character, the program checks whether the input character is lowercase or uppercase. Для каждого случая предусмотрено отдельное сообщение. A message appears for each case.
Пример Example
Можно также поместить оператор if в блок else, как показано в части кода, приведенной ниже. You can also nest an if statement inside an else block, as the following partial code shows. В примере операторы if помещаются в два блока else и один блок then. The example nests if statements inside two else blocks and one then block. Комментарии определяют какие условия выполняются в каждом из блоков. The comments specify which conditions are true or false in each block.
Пример Example
В приведенном ниже примере определяется, является ли введенный символ строчной буквой, прописной буквой или цифрой. The following example determines whether an input character is a lowercase letter, an uppercase letter, or a number. Если все три условия имеют значение false, то символ не является алфавитно-цифровым. If all three conditions are false, the character isn’t an alphanumeric character. Для каждого случая выводится сообщение. The example displays a message for each case.
Точно так же как оператор в блоке else или блоке then может быть любым допустимым оператором, в качестве условия можно использовать любое допустимое логическое выражение. Just as a statement in the else block or the then block can be any valid statement, you can use any valid Boolean expression for the condition. Вы можете использовать логические операторы, такие как ! , && , || , & , | и ^ , для формирования составных условий. You can use logical operators such as ! , && , || , & , | , and ^ to make compound conditions. В коде ниже приведены примеры. The following code shows examples.
Спецификация языка C# C# language specification
Дополнительные сведения см. в спецификации языка C#. For more information, see the C# Language Specification. Спецификация языка является предписывающим источником информации о синтаксисе и использовании языка C#. The language specification is the definitive source for C# syntax and usage.
директивы #if, #elif, #else и #endif (C/C++) #if, #elif, #else, and #endif directives (C/C++)
Директива #if с директивами #elif, #else и #endif управляет компиляцией частей исходного файла. The #if directive, with the #elif, #else, and #endif directives, controls compilation of portions of a source file. Если выражение, которое вы пишете (после #if), имеет ненулевое значение, группа строк сразу после директивы #if сохраняется в записи преобразования. If the expression you write (after the #if) has a nonzero value, the line group immediately following the #if directive is kept in the translation unit.
Грамматика Grammar
условное : conditional :
Если-Part elif — Parts to else-Part (неявное согласие ) — строка if-part elif-partsopt else-partopt endif-line
If-Part : if-part :
текст в виде строки if-line text
If-Line : if-line :
#if константное выражение #if constant-expression
идентификатор #ifdef #ifdef identifier
идентификатор #ifndef #ifndef identifier
elif — части : elif-parts :
elif — текст строки elif-line text
elif-Parts elif — текст строки elif-parts elif-line text
elif-строка : elif-line :
#elif константное выражение #elif constant-expression
else-Part : else-part :
текст в else-строке else-line text
else-Line : else-line :
#else #else
endif-строка : endif-line :
#endif #endif
Комментарии Remarks
Каждая директива #if в исходном файле должна соответствовать закрывающей директиве #endif . Each #if directive in a source file must be matched by a closing #endif directive. Между директивами #if и #endif может использоваться любое число директив #elif , но допускается не более одной директивы #else . Any number of #elif directives can appear between the #if and #endif directives, but at most one #else directive is allowed. Директива #else , если она есть, должна быть последней директивой перед #endif. The #else directive, if present, must be the last directive before #endif.
Директивы #if, #elif, #else и #endif могут быть вложены в текстовые части других директив #if . The #if, #elif, #else, and #endif directives can nest in the text portions of other #if directives. Каждая вложенная директива #else, #elif или #endif принадлежит ближайшей предшествующей директиве #if . Each nested #else, #elif, or #endif directive belongs to the closest preceding #if directive.
Все директивы условной компиляции, такие как #if и #ifdef, должны соответствовать закрывающей директиве #endif перед концом файла. All conditional-compilation directives, such as #if and #ifdef, must match a closing #endif directive before the end of file. В противном случае создается сообщение об ошибке. Otherwise, an error message is generated. Если директивы условной компиляции содержатся во включаемых файлах, они должны удовлетворять одинаковым условиям: в конце включаемого файла не должно оставаться непарных директив условной компиляции. When conditional-compilation directives are contained in include files, they must satisfy the same conditions: There must be no unmatched conditional-compilation directives at the end of the include file.
Замена макросов выполняется в части строки, следующей за командой #elif , поэтому в константном выражении можно использовать вызов макроса. Macro replacement is done within the part of the line that follows an #elif command, so a macro call can be used in the constant-expression.
Препроцессор выбирает один из заданных вхождений текста для дальнейшей обработки. The preprocessor selects one of the given occurrences of text for further processing. Блок, указанный в тексте , может быть любой последовательностью текста. A block specified in text can be any sequence of text. Он может занимать несколько строк. It can occupy more than one line. Обычно текст — это текст программы, который имеет значение для компилятора или препроцессора. Usually text is program text that has meaning to the compiler or the preprocessor.
Препроцессор обрабатывает выбранный текст и передает его компилятору. The preprocessor processes the selected text and passes it to the compiler. Если текст содержит директивы препроцессора, препроцессор выполняет эти директивы. If text contains preprocessor directives, the preprocessor carries out those directives. Компилируются только текстовые блоки, выбранные препроцессором. Only text blocks selected by the preprocessor are compiled.
Препроцессор выбирает один текстовый элемент, оценивая константное выражение после каждой директивы #if или #elif , пока не найдет истинное (ненулевое) константное выражение. The preprocessor selects a single text item by evaluating the constant expression following each #if or #elif directive until it finds a true (nonzero) constant expression. Он выбирает весь текст (включая другие директивы препроцессора, начинающиеся с # ) со связанными #elif, #else или #endif. It selects all text (including other preprocessor directives beginning with #) up to its associated #elif, #else, or #endif.
Если все вхождения константного выражения имеют значение false или если директивы #elif не отображаются, препроцессор выбирает блок текста после предложения #else . If all occurrences of constant-expression are false, or if no #elif directives appear, the preprocessor selects the text block after the #else clause. Если отсутствует предложение #else , а все экземпляры константного выражения в блоке #if имеют значение false, то текстовый блок не выбирается. When there’s no #else clause, and all instances of constant-expression in the #if block are false, no text block is selected.
Константное выражение является целочисленным константным выражением с этими дополнительными ограничениями: The constant-expression is an integer constant expression with these additional restrictions:
Выражения должны иметь целочисленный тип и могут включать только целочисленные константы, символьные константы и определенный оператор. Expressions must have integral type and can include only integer constants, character constants, and the defined operator.
Выражение не может использовать sizeof или быть оператором приведения типа. The expression can’t use sizeof or a type-cast operator.
Целевая среда может не представлять все диапазоны целых чисел. The target environment may be unable to represent all ranges of integers.
Преобразование представляет тип так int же, как и тип long , и так unsigned int же, как и unsigned long . The translation represents type int the same way as type long , and unsigned int the same way as unsigned long .
Транслятор может преобразовывать символьные константы в набор кодовых значений, отличающийся от набора для целевой среды. The translator can translate character constants to a set of code values different from the set for the target environment. Чтобы определить свойства целевой среды, используйте приложение, созданное для этой среды, чтобы проверить значения ограничений. H макросы. To determine the properties of the target environment, use an app built for that environment to check the values of the LIMITS.H macros.
Выражение не должно запрашивать среду и должно оставаться изолированным от сведений о реализации на целевом компьютере. The expression must not query the environment, and must remain insulated from implementation details on the target computer.
Операторы препроцессора Preprocessor operators
defined defined
Определяемый Оператор препроцессора можно использовать в специальных константных выражениях, как показано в следующем синтаксисе: The preprocessor operator defined can be used in special constant expressions, as shown by the following syntax:
определено ( идентификатор ) defined( identifier )
определенный идентификатор defined identifier
Это константное выражение считается истинным (ненулевым), если идентификатор в настоящее время определен. This constant expression is considered true (nonzero) if the identifier is currently defined. В противном случае условие не выполняется (false, значение равно 0). Otherwise, the condition is false (0). Идентификатор, определенный как пустой текст, считается определенным. An identifier defined as empty text is considered defined. Определенный оператор может использоваться в #if и директиве #elif , но нигде не используется. The defined operator can be used in an #if and an #elif directive, but nowhere else.
В следующем примере директивы #if и #endif управляют компиляцией одного из трех вызовов функций: In the following example, the #if and #endif directives control compilation of one of three function calls:
Вызов функции credit компилируется, если определен идентификатор CREDIT . The function call to credit is compiled if the identifier CREDIT is defined. Если определен идентификатор DEBIT , компилируется вызов функции debit . If the identifier DEBIT is defined, the function call to debit is compiled. Если ни один из этих идентификаторов не определен, компилируется вызов функции printerror . If neither identifier is defined, the call to printerror is compiled. CREDIT И credit , и — это разные идентификаторы в C и C++, так как их варианты различны. Both CREDIT and credit are distinct identifiers in C and C++ because their cases are different.
В следующем примере в операторах условной компиляции используется ранее определенная символьная константа с именем DLEVEL . The conditional compilation statements in the following example assume a previously defined symbolic constant named DLEVEL .
В первом блоке #if показаны два набора вложенных директив #if, #else и #endif . The first #if block shows two sets of nested #if, #else, and #endif directives. Первый набор директив обрабатывается только в том случае, если выполняется условие DLEVEL > 5 . The first set of directives is processed only if DLEVEL > 5 is true. В противном случае обрабатываются инструкции после #else . Otherwise, the statements after #else are processed.
Директивы #elif и #else во втором примере используются, чтобы выбрать один из четырех вариантов в зависимости от значения DLEVEL . The #elif and #else directives in the second example are used to make one of four choices, based on the value of DLEVEL . Константе STACK присваивается значение 0, 100 или 200 в зависимости от определения константы DLEVEL . The constant STACK is set to 0, 100, or 200, depending on the definition of DLEVEL . Если DLEVEL больше 5, то компилируется оператор If DLEVEL is greater than 5, then the statement
компилируется и STACK не определяется. is compiled, and STACK isn’t defined.
Условная компиляция обычно используется для предотвращения нескольких включений одного и того же файла заголовка. A common use for conditional compilation is to prevent multiple inclusions of the same header file. В C++, где классы часто определяются в файлах заголовков, такие конструкции можно использовать для предотвращения нескольких определений: In C++, where classes are often defined in header files, constructs like this one can be used to prevent multiple definitions:
Предыдущий код проверяет, определена ли символьная константа EXAMPLE_H . The preceding code checks to see if the symbolic constant EXAMPLE_H is defined. Если да, то файл уже включен и не нуждается в повторной обработке. If so, the file has already been included and doesn’t need reprocessing. Если нет, константа EXAMPLE_H определяется, чтобы пометить файл EXAMPLE.H как уже обработанный. If not, the constant EXAMPLE_H is defined to mark EXAMPLE.H as already processed.
__has_include __has_include
Visual Studio 2017 версии 15,3 и более поздних версий: определяет, доступен ли заголовок библиотеки для включения: Visual Studio 2017 version 15.3 and later: Determines whether a library header is available for inclusion: