C--Conditional Statements
Posted jllin
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C--Conditional Statements相关的知识,希望对你有一定的参考价值。
Conditionals
Conditional expressions allow your programs to make decisions and take different forks in the road,depending on the value of variables or user input.
C provides a few different ways to implement conditional expressions (also know as branches ) in your programs,some of which likely look familiar from Scratch.
if (and if-else,and if-else..else)
Use Boolean expressions to make descisions.
if (boolean-expression)
{
statements;
}
if the boolean-expression evaluates to true,all lines of code between the curly braces will execute in order from top-to-bottom.
if the boolean-expression evaluates to false,those lines of code will not execute.
if (boolean-expression)
{
statements;
}
else
{
statements;
}
if the boolean-expression evaluates to true,all lines of code between the first set of curly braces will execute in order from top-to-bottom.
if the boolean-expression evaluates to false,all lines of code between the second set of curly braces will execute in order from top-to-bottom.
switch statement
Use discrete cases to make decisions
int x = GetInt();
switch(x)
{
case 1;
printf("One! ");
break;
case 2:
printf("Two! ");
break;
case 3:
printf("Three! ");
break;
default:
printf("Sorry! ");
}
C‘s switch() statement is a conditional statement that permits enumeration of discrete cases,instead of relying on Boolean expressions.
It‘s important to break;between each case,or you will "fall throug" each case (unless that is desired behavior).
The ternary operator (?:)
Use to replace a very simple if-else to make your code look fancy
cool but not a good idea
int x;
if (expr)
{
x = 5;
}
else
{
x = 5;
}
Next
int x = (expr) ? 5 : 6;
These two snippets of code act identically. // 这两段代码片段作用相同
The ternary operator (?:) is mostly a cute trick,but is useful for writing tricially short conditional branches.Be familiar with it,but know that you won‘t need to write it if you don‘t want to. // 三元操作符(?:)是一个不错的技巧
以上是关于C--Conditional Statements的主要内容,如果未能解决你的问题,请参考以下文章
使用 pg_stat_statements 收集大型统计集?
如何处理 R0915: Too many statements (69/50) (too-many-statements) in pylint?