Is the below syntax of writing do while loop containing single statement without using braces like other loops namely while, for, etc. correct? I'm getting the required output but I want to know whether this has any undefined behavior.
int32_t i = 1;
do
std::cout << i << std::endl;
while(++i <= 10);
The original resource to answer this question should be the C++ standards: http://www.open-std.org/jtc1/sc22/wg21/docs/standards.
In C++17, 9.5 Iteration statements [stmt.iter] says do takes a statement:
do statement while ( expression ) ;
So this is definitely fine.
9.3 Compound statement or block [stmt.block] says
So that several statements can be used where one is expected, the compound statement (also, and equivalently,
called “block”) is provided.
so people tend/like to use { ... } for do statements.
The grammar for a do-while loop is given here:
do statement while ( expression ) ;
The grammar for a statement allows for a expression-statement:
statement:
attribute-specifier-seq opt expression-statement
expression-statement:
expression opt ;
So the body of a do-while doesn't need to be inside {}, and your code is valid.
cppreference indicates that it's the same with do while as it is with while and if and so on.
The relevant syntax:
attr (optional) do statement while ( expression ) ;
attr(C++11) - any number of attributes
expression - any expression which is contextually convertible to bool.
This expression is evaluated after each iteration, and if it yields false, the loop is exited.
statement - any statement, typically a
compound statement, which is the body of the loop
The key here is that a statement is typically a compound statement enclosed in curly braces, but not necessarily so.
As with those constructions, I would tend to prefer braces even when it is only a single line, but it's good to know that it works.
If you have only one statement inside the do-while or if or for, the braces aren't necessary
i.e.
do
statement;
while (cond)
is the same as
do
{
statement;
}
while (cond)
One the other hand
Likewise
if(cond)
statement;
is same
if(cond)
{
statement;
}
If you write
if(cond)
statement1;
statement2;
Then this will considered as
if(cond)
{
statement1;
}
statement2;
The body of a do-while construct must be a statement.
attr(optional) do statement while ( expression ) ;
attr(C++11) - any number of attributes
expression - any expression which is contextually convertible to bool. This expression is evaluated after each iteration, and if it yields false, the loop is exited.
statement - any statement, typically a compound statement, which is the body of the loop
cppreference notes that this statement is usually a compound statement, which is a block surrounded by curly braces.
Compound statements or blocks are brace-enclosed sequences of statements.
However, this statement can also just be an expression terminated by a semi-colon, which is the case in your example.
No, it's completely fine!
Any loop in C++ which expects curly braces and doesn't find them takes the first line into consideration and move on.
Related
#include<stdio.h>
int main(void)
{
int x=1,y=0;
x>y?printf("Hello World"):return x;
}
Why it shows error: expected expression before ‘return’?
What is the thing need to be changed here?
Why it shows error: expected expression before ‘return’?
The ternary operator is an operator, requiring three operands. The first operand must be an expression of integer type. The latter two operands must be expressions of type compatible with each other.
A return statement specifies a return value for the function in which it appears, and causes that function to terminate. It is not an expression, and does not evaluate to a value, neither the specified return value or any other. As such, it cannot be an operand of the ternary operator.
The error message is, therefore, expressing that the third operand of the ternary operator is missing, which it is, since the return statement cannot be considered an operand. If it were present, that operand would appear before the return.
What is the thing need to be changed here?
To obtain the logic you appear to want, the thing to change is the ternary operator. Use an if / else statement instead:
if (x > y) {
printf("Hello World");
} else {
return x;
}
Generally speaking, the ternary operator should be avoided. It usually makes code harder to read and understand, with little or no offsetting benefit. You may someday discover a programming context where a ternary is the cleanest, clearest way to go, but anywhere else, use if.
The main theme of the ternary operator is
condition ? value_if_true : value_if_false
The statement evaluates to value_if_true if the condition is met, and value_if_false otherwise.
Read more about 'ternary operator' [https://www.freecodecamp.org/news/c-ternary-operator/]
Try to avoid a ternary operator if your concept is not clear. Try to use if-else.
int main() {
int a;
2;
4;
a;
return 0;
}
Why is this piece of code valid (i.e. not raising any compilation error) ? What the computer does when executing 1; or a; ?
Statements like 0;, 4; are no-operations.
Note that the behaviour of your program is undefined since a; is a read of the uninitialised variable a. Oops.
0, for example, is a valid expression (it's an octal literal int type with a value zero).
And a statement can be an expression followed by a semi-colon.
Hence
0;
is a legal statement. It is what it is really. Of course, to change the language now to disallow such things could break existing code. And there probably wasn't much appetite to disallow such things in the formative years of C either. Any reasonable compiler will optimise out such statements.
(One place where you need at least one statement is in a switch block body. ; on its own could issue warnings with some compilers, so 0; could have its uses.)
They are expression statements, statements consisting of an expression followed by a semicolon. Many statements (like a = 3;, or printf("Hello, World!");) are also expression statements, and are written because they have useful side effects.
As for what the computer does, we can examine the assembly generated by the compiler, and can see that when the expression has no side effects, the compiler is able to (and does) optimise the statements out.
I am trying to understand thoroughly the difference between a statement and an expression
But i am finding it confusing even after reading this answer
Expression Versus Statement
look at the following:
std::cout << "Hello there? " ;
I could say that it is a statement as it is ending with a semi- colon BUT i could also say
It is an expression since i have an ostream , an output operator and a string literal
and this expression yields a value which is the left hand operand.
Which one is correct?
Let's see what the C++ grammar can tell us:
statement:
labeled-statement
attribute-specifier-seq_opt expression-statement
attribute-specifier-seq_opt compount-statement
attribute-specifier-seq_opt selection-statement
attribute-specifier-seq_opt iteration-statement
attribute-specifier-seq_opt jump-statement
declaration-statement
attribute-specifier-seq_opt try-block
expression-statement:
expression_opt ';'
So it is a statement; in particular, an "expression statement", which consists of a (potentially empty) expression followed by a semi-colon. In other words,
std::cout << "Hello there? "
is an expression, while
std::cout << "Hello there? " ;
is a statement.
Which one is correct?
Both: it is an expression statement. C and C++ let you put an expression into a body of code, add a semicolon, and make it a statement.
Here are some more examples:
x++; // post-increment produces a value which you could use
a = 5; // Assignment produces a value
max(a, b); // Call of a non-void function is an expression
2 + x; // This calculation has no side effects, but it is allowed
Note that this is true in the specific case of C and C++, but may not be true in case of other languages. For example, the last expression statement from the list above would be considered invalid in Java or C#.
The definition of expression is given in the C Standard (6.5 Expressions)
1 An expression is a sequence of operators and operands that specifies
computation of a value, or that designates an object or a function, or
that generates side effects, or that performs a combination thereof.
The value computations of the operands of an operator are sequenced
before the value computation of the result of the operator.
As for expression-statements then they are ended with a semicolon. Here is the definition of the expression statement in C++
expression-statement:
expression opt;
And
An expression statement with the expression missing is called a null
statement.
Relative to the last quote I would like to point to a difference between C and C++. In C++ declarations are statements while in C declarations are not statements. So in C++ you may place a label before a declaration while in C you may not do so. So in C you have to place a null statement before a declaration. Compare
C++
Label:
int x;
C
Label: ;
int x;
I was going through someone elses code and I wasn't able to get the syntax of following
c = x<0 ? x = -x,'L':'R';
and
if(x) x--,putchar(c);
going by the symantics, it is clear that in the first, variable c is assigned 'L' or 'R'.And in the second, both x-- and putchar() are executed. But what exactly is the role of comma operator here??
But what exactly is the role of comma operator here?
In this case, code obfuscation. The original developer probably thought they were being clever.
The comma operator allows you to perform multiple actions in a single statement, but you are almost always better off using 2 statements. In those cases, it expands to:
if( x < 0 ) {
x = -x;
c = 'L';
} else {
c = 'R';
}
and
if(x) {
x--;
putchar(c);
}
The comma operator evaluates both expressions, and returns the value of the last.
The first expression does two things in one statement. If chooses 'L'
or 'R' and also sets x to its negative if 'L' is chosen.
The second expression (the part after the 'if') decrements x and then
puts a character. The meaning of this is unclear without more context.
Readability in both could be improved by using separate statements rather than the comma operator. The first tries to shoehorn an if statement into a conditional expression. But the second is already using an if statement, so it's unclear why the comma operator was chosen at all.
The role of the comma operator in that context is to allow using the conditional operator and write an assignment as part of the evaluation of one of the expressions.
In my opinion, this is just horrible style. An if statement would have better communicated the intent of that code, and would have hardly been less efficient.
The Question :
In programming , assignment statement is an expression , but how about initialization?Is it an expression??
the parentheses of a while loop should contain an expression , so i try to put an initialization into it , and the compiler prompt me an error , this shows initialization is not an expression.
To further prove it , i try the for loop , and i do this for(int num = 3 ; num2 = 4 ; num3 = 5).Surprisingly the compiler give me errors again.
So if an initialization is not an expression , what kind of statement it is??
Thanks for spending time reading my question
In both C and C++, assignment is an expression. E.g. a = 5 is an assignment-expression.
In both C and C++ you can use any expression followed by a semi-colon where statement is required - such as the body of a function. This type of statement is an expression-statement. (Technially, you can leave out the expression entirely. ; is a degenerate expression-statement.)
You can only use a declaration where a declaration is expected, not everywhere where you can use an expression.
The following is not an expression or an expression-statement, it is a declaration. (Technically, in C++, it can form a declaration-statement when used where a statement is expected, in C it is just a declaration.) Note that there is no assignment-expression sub-part to this declaration, = 3 is an initializer for the declared entity num.
int num = 3;
These two common uses of = (initialization and assignment) are sometimes confused. Where = is being used to initialize the entity being declared in a declaration, it is initialization, where it is being used to change the value of an already declared entity, it is assignment.
Here is where C and C++ differ: in C, the parenthesised entity immediately following the while keyword must be an expression so something like while (int num = 0) { /* ... */ } is not valid.
In C++ the entity can be a condition, which allows for a simple declaration with an initializer as well as a simple expression, as in C. In C++, where the condition is in the form of a declaration, the declared entity is initialized on each iteration and implicitly converted to bool to determine whether to execute the loop body.
The for loop is special in both languages. In both languages the first part of the parenthesized list following the for keyword can effectively be either a declaration or an expression-statement.
The for loop takes three expressions in C and C++. The first is executed before the loop is run. The value of the second is used to determine when the loop ends. The third expression is executed at the end of each iteration of the for loop.
You can abuse the intent of the for loop and put whatever expression you want in those three sections.
The while loop while(<expression>) {<body>} is equivalent to the for loop for(;<expression>;) {<body>}.