I am reading a code of my friend an I see this:
#include <stdio.h>
#include <conio.h>
void main()
{
char string1[125], string2 [10];
int i, j;
printf("\nstring 1: ");
gets(string1);
printf("\nNstring2 : ");
gets(string2);
i = 0;
while (string1[i] != 0)
{
j = 0;
while (string1[i++] == string2[j++] &&string1[i-1] != 0 && string2[j-1] != 0)
;//i dont know what it mean and why we can put ;after while loop
if (string1[i-1] != 0 && string2[j-1] == 0)
printf("\nfound at position %d", i-j);
}
getch();
}
why we can put ; after while loop , anyone can help?
The ; is just a null statement, it is a no op but it it the body of the while loop. From the draft C99 standard section 6.8.3 Expression and null statements:
A null statement (consisting of just a semicolon) performs no operations.
and a while statement is defined as follows from section 6.8.5 Iteration statements:
while ( expression ) statement
So in this case the statement of the while loop is ;.
The main effect of the while loop is here:
string1[i++] == string2[j++]
^^^ ^^^
So each iteration of the loop increments i and j until the whole condition:
string1[i++] == string2[j++] &&string1[i-1] != 0 && string2[j-1] != 0
evaluates to false.
Usually, in a while loop, you have initialization, a comparison check, the loop body (some processing), and the iterator (usually either an addition of an index, or a pointer traversal e.g. next), something like this:
index = 0 // initialization
while(index < 4) { // comparison, loop termination check
printf('%c\n', mystring[index]); // Some processing
index += 1; // iterate to next loop
}
Without at least the last item, you won't ever exit the loop, so normally the loop body has more than one statement in it. In this case, they use post-increments like this:
while (string1[i++] == string2[j++]);
This does the comparison (the ==) and the iteration (the post-increment ++) in the comparison statement itself, and has no body, so there's no reason to add any other statements. A blank loop body can be represented by just a semicolon.
Semicolon is like empty instruction. If we don't put any instruction after while or use loop while with {} we must use semicolon to tell compiler that all we want from while loop is doing this empty instruction.
That is called a semicolon. In programming standards, the ; signifies an end of statement, or in this case that it is a null statement. It is effectively a non operation in the body of the while loop, so it is not actually doing anything.
Related
The semicolon has been added after the first while loop, but why is the value of the i variable 3 here, where j is 2?
#include<stdio.h>
int main()
{
int i=1;
while(i++<=1);
printf("%d",i);
int j=1;
while(j++<=1)
printf("%d",j);
return 0;
}
Both while loops run once (and once only); the difference is that, in the second case (the j loop) you are printing the 'control variable' inside the loop but, for the first case, you are printing it after the loop condition has evaluated to false. Also note that, in the first case, the semicolon immediately following the while statement defines the body of that loop as empty1.
Let's break down the first loop into steps:
On the first test of the condition, i++ evaluates to 1 and then i is incremented – so the loop runs.
On the second test, i++ evaluates to 2 (so the loop doesn't run) but i is still (post-)incremented, leaving it with the value of 3 (as shown in the output).
The same thing happens with j in the second loop but, in that case, as previously mentioned, you are displaying the value in the body of the loop (on its only run), so you see the value after the first (post-)increment.
As noted in the comments, if you add another printf("%d", j); after the body of the loop (which, in that case, consists of a single statement), you will see that j, too, has the value 3 when that loop has finished.
1 More precisely, the semicolon (on its own) defines a null statement, which forms the body of the while loop.
It is often helpful to clarify such 'null loops' by putting the semicolon on a line by itself (some compilers, with full warnings or static analysis enabled, may even suggest you do this):
#include<stdio.h>
int main()
{
int i = 1;
while (i++ <= 1)
; // Body of loop - Null Statement
printf("%d", i); // Loop has finished
int j = 1;
while (j++ <= 1)
printf("%d", j); // Body of loop
// Loop has finished
return 0;
}
For starters let;s consider how the postfix increment operator works. From the C Standard (6.5.2.4 Postfix increment and decrement operators)
2 The result of the postfix ++ operator is the value of the
operand. As a side effect, the value of the operand object is
incremented (that is, the value 1 of the appropriate type is added to
it).
Now consider this while loop
int i=1;
while(i++<=1);
In the first iteration of the loop the value of the expression i++ as the value of its operand that is 1. So the loop will iterate a second time, Due to applying the side effect to the variable i it will be equal already to 2 when the expression i++<=1 will evaluate the second time.
Now the value of i is equal to 2 and is greater than 1. so the loop will be interrupted. Again due to applying the side effect of the postfix increment operator to the variable i it will be equal to 3. This value is outputted in the following call of printf.
In simplest terms,
consider three things for each iteration of first while loop:
first iteration:
int i = 1;//initialization
while(i++<=1); //1. i evaluated as 1,
//2. loop condition is true causing loop to iterate again.
//3. ...but not before ++ causes i==2.
second iteration:
while(i++<=1); //1. i evaluated as 2,
//2. loop condition is false causing loop to eventually exit
//3. ...but not before ++ causes i==3.
printf is not included in the while loop (because of the semicolon) but
when program flow finally reaches printf("%d",i); the value of i is output as 3
In the second loop, because printf is included in the while construct, it will output the value of j for each iteration. For the same reasons as in loop one, it will also iterate only twice, and its values at time of output will be 2 & 3.
Using a debugger to set break points, and a watch on i, you can step through code such as this to see the sequence of these effects as they happen.
For explanation porpouses look at this example:
int main()
{
int i=1;
while(i++<=1)
printf("%d",i);
printf("%d",i);
}
The Output is:
2
3
Ok let's dive into the programm procedure:
Declaring i (i = 1)
while checking Condition and it's true because i++ returns 1(old Value). That's because the ++ are after the i. If you would code it like this ++i than it returns 2(new Value) (i = 2)
execute printf (i = 2)
while checking Condition and it's false because i++ returns 2 and 2 is not <= 1 (i = 3)
execute printf (i = 3)
Do you understand?
If it solved your thoughts jumble ;) mark it as answer.
You've got many answers already so I won't try to explain it in words but with an illustration in code. I've added two functions:
One that acts like a prefix increment operator (++i)
One that acts like a postfix increment operator (i++)
I'm only using the postfix version in the program though. I've added logging to the function so you can see how it works.
#include <stdio.h>
// this acts as if you put ++ before the variable
int preinc(int* p) {
++*p;
return *p;
}
// this acts as if you put ++ after the variable
int postinc(int* p) {
int rv = *p;
++*p;
printf("returning %d but incremented to %d\n", rv, *p);
return rv;
}
int main() {
int i=1;
while(postinc(&i) <= 1);
printf("end result: %d\n---\n", i);
int j=1;
while(postinc(&j) <= 1)
printf("in loop: %d\n", j);
printf("end result: %d\n", j);
}
Output:
returning 1 but incremented to 2
returning 2 but incremented to 3
end result: 3
---
returning 1 but incremented to 2
in loop: 2
returning 2 but incremented to 3
end result: 3
If you add the semicolon in the end of the while you will take: i = 3 and j = 3(IN THE OUTPUT).
If you add the semicolon only in the end of the printf and not to the while you will take i = 2 and j = 2(IN THE OUTPUT), but in the end you will, also, have the values
i = 3 and j = 3.
This happens because the "i" variable is incremented only after the first iteration of the loop, in which the empty statement (terminated by the semicolon) is evaluated.
that is why it is highly recommended to do "++i" rather than "i++", because then the incrementation is performed prior to the evaluation.
if you flip it here, you will see that i will be equal to 2 as well, regardless of the presence of the semicolon
I want to know exactly, what is a null statement in C programming language? And explain a typical use of it.
I found the following segment of code.
for (j=6; j>0; j++)
;
And
for (j=6; j>0; j++)
From the msdn page:
The "null statement" is an expression statement with the expression missing. It is useful when the syntax of the language calls for a statement but no expression evaluation. It consists of a semicolon.
Null statements are commonly used as placeholders in iteration statements or as statements on which to place labels at the end of compound statements or functions.
know more: https://msdn.microsoft.com/en-us/library/1zea45ac.aspx
And explain a typical use of it.
When you want to find the index of first occurrence of a certain character in a string
int a[50] = "lord of the rings";
int i;
for(i = 0; a[i] != 't'; i++)
;//null statement
//as no operation is required
A null statement is a statement that doesn't do anything, but exists for syntactical reasons.
while ((*s++ = *t++))
; /* null statement */
In this case the null statement provides the body of the while loop.
or (disclaimer: bad code)
if (condition1)
if (condition2)
dosomething();
else
; /* null statement */
else
dosomethingelse();
In this case the inner else and null statement keeps the outer else from binding to the inner if.
From C11, §6.8.4.1, 6.8.3 Expression and null statements:
A null statement (consisting of just a semicolon) performs no
operations.
The standard also provides a couple of common uses of it:
EXAMPLE 2 In the program fragment
char *s;
/* ... */
while (*s++ != '\0')
;
a null statement is used to supply an empty loop body to the iteration
statement.
6 EXAMPLE 3 A null statement may also be used to carry a label just
before the closing } of a compound statement.
while (loop1) {
/* ... */
while (loop2) {
/* ... */
if (want_out)
goto end_loop1;
/* ... */
}
/* ... */
end_loop1: ;
}
A null statement doesn't DO anything, hence the solo ';'
so....this code block will do nothing 10x in C/C++
for(int i = 0; i < 10; i++){//execute the following 10 times
;//nothing aka "null statement"
}//end for
Sometimes the null statement serves. In the "old days" the math hardware might not return an integer value when you needed one, such as returning 0.999... as sin(pi / 2), (that is sin(90 degrees)).
int i, j, k;
i = something;
for(j = 1; (2 * j) <= i; j *= 2);
Computes in j the largest integer power of 2 less than i. Not very efficient for large i but useful if you could not trust Log functions to return an exact integer value.
My C++ compiler does not accept the null statement as a function body, but does accept the "empty statement" which I think is just an empty statement block "{}".
Whether C or java, null has a special significance.
Whenever there is a need of re-intializing of values to variavle, null serves the purpose.
If there is a String i, and we want it to add a char value through a loop, then first we have to intialize i with null.
How this for loop is working
int main(){
char i=0;
for(i<=5 && i>=-1; ++i ;i>0)
printf("%d \n",i);
printf("\n");
return 0;
}
Ahh thanks for the clarification.
Your asking why the for loop in your example is executing, even though the increment operand and loop condition have been swapped, and the fact that the variable is a char. Lets consider the proper structure of a for loop:
for (initialise variable; for condition; increment variable)
{
//Do stuff
}
The answer to your question is simple:
Your condition increases i by 1, but as you have pointed out, i is a char. Using operands on a char can convert it to another type, including int (refer C comparison char and int)
A loop will continue until its condition == false.
Your loop will continue running until i=0, which means it will continue to increase by 1 until it reaches 128, at which point it will overflow to -128 and continue to increase until it reaches 0 again.
Lets name parts of the for loop:
for( Expr1; Expr2; Expr3 )
DoStuff;
This is how a for loop works:
1. It executes Expr1 first. in your loop does nothing in fact, since it doesn't check the result of this execution.
Then it executes Expr2 and treat it's result as a condition if it's 0 terminates the loop, if it's "not 0" go to step 3. In your loop this means that i will be incremented, thus it's now 1, so result is true.
Then it runs the DoStuff part, in your case print out i value
Next it executes Expr3, no check, just run it, in your case does nothing again, since it's a condition and its result isn't used.
Next it goes back to Expr2 executes it and check it's result. now i is 2, still a true condition.
Again execute the DoStuff part and go to step 4
The loop will stop once i value changes back to 0.
When? since it's type is char, after reaching 127 it will overflow to -128 and then increment back to -1 and then 0. and stop.
Whenever you want to understand for loop in this kind of situation you can convert for loop into while to understand it.
The for syntax is:
for (initialization; condition; operation)
...
It can be converted into while as:
initialization;
while (condition) {
...
operation;
}
So in your case
i <= 5 && i >= -1; // Initialization
while(++i) { //condition
printf("%d \n", i);
i > 0; // operation
}
Initialization part will be execute once it will check for condition.Here in your case it is ++i so increment every time.Here i>0 means if i==0 then loop will stop it does not matter i is positive or negative Thumb rule to remember in this kind of situation is if (i == 0 ) then true else false. i>0 remains true)in every case after that so loop is infinite.
To understand for loop best answer I have seen in SO is this
There's not rule about the order of for loop condition and increment operation, the latter even don't need to be an increment operation. What it's expected to do is determined by you. The code is just same as the following semantically.
char i = 0;
i <= 5 && i >= -1; // Run before the loop and only once. No real effect here.
while (++i) { // Condition used to determine the loop should continue or break
printf("%d \n", i);
i > 0; // Run every time inside the loop. No real effect here.
}
BTW: It'll be an infinite loop (because ++i is a nonzero value until overflow).
I found the following code:
int func_prim (int zahl) {
int count;
if (zahl < 0)
return -1;
for (count = 2; zahl % count != 0 && zahl >= count; count++);
if (count == zahl)
return 1;
return 0;
}
The point of function is to check whether a number is a prime number or not.
I don't understand why the for-loop has ; at the end:
v
for (count = 2; zahl % count != 0 && zahl >= count; count++);
Without that, the code doesn't work properly.
What is the explanation?
It means exactly the same as:
for(count = 2; zahl % count != 0 && zahl >= count; count++)
{
}
A for loop has the for keyword, followed by parentheses containing three optional expressions separated by semicolons, followed by a body which executes in each iteration of the loop.
The goal of the for loop in your example is to set the value of count, which will be compared to zahl in the if statement that follows. This is achieved in the semicolon-delimited expressions, so the loop body doesn't need to do anything.
Since the loop doesn't need to do anything, it uses the empty statement as its body.
If the ; at the end were omitted and no other changes were made, then the if statement after the for loop would itself become the body of the for loop. (That is not intended and would break the program, as you have observed.)
However, making one's loop body consist of a single ; on the same line is not the only way to write an empty loop body, nor is it probably the most sensible way to do so. It works perfectly well, but the problem is that other readers - and perhaps the same programmer, returning to the project later - may wonder if it was actually an error. After all, one types semicolons at the ends of lines quite often when coding in a C-style language, so it's easy to type an extra one where it doesn't belong.
The other problem is that, in code where a one-line loop with ; as its body is the chosen style, it is difficult to recognize when someone actually has made the mistake of putting a ; when one doesn't belong.
Therefore, these alternatives may be preferable:
putting the ;, indented, on the next line -- as sh1 suggests
writing the loop body as an empty block, { }, rather than an empty statement
making the loop body a continue; statement, which simply causes the loop to move on to its next iteration (which is the same as what happens when the loop body is empty) -- also as sh1 suggests
The semicolon at the end of the for-loop means it has no body. Without this semicolon, C thinks the if statement is the body of the for loop.
Syntax of for loop (iteration statement) is
for ( clause-1 ; expression-2 ; expression-3 ) statement
statement can be a null statement (;). C11 6.8.3 says
A null statement (consisting of just a semicolon) performs no operations.
In para 5 it gives an example
In the program fragment
char *s;
/* ... */
while (*s++ != '\0')
;
a null statement is used to supply an empty loop body to the iteration statement.
Same thing is happening in
for (count = 2; zahl % count != 0 && zahl >= count; count++);
; is used to supply an empty loop body to the for statement. Without ; the statement next to the for loop will be considered as its body and will be executed.
In addition to what the other excellent answers already say, I would like to point out that
for(count=2; zahl % count != 0 && zahl >= count; count++);
(that is, a for loop with an empty statement used to increment a "counter") is equivalent to
count=2;
while(zahl % count != 0 && zahl >= count)
{
count++;
}
that would make the objective of the code even clearer than some of the listed alternatives: if not comments are present, as in the presented case, a loop with an empty statement might confuse another programmer that has to mantain or use the code (as was the case with the OP here).
The context might help discerning the true scope of the statement, but between a for loop with an empty statement and a while loop with a statement, the latter requires less work to understand its scope.
The ; after the for loop simply means that the for loop won't do anything more than increase the counter count.
for Statement:
The for statement is a loop statement whose structure allows easy
variable initialization, expression testing, and variable
modification. It is very convenient for making counter-controlled
loops. Here is the general form of the for statement:
for (initialize; test; step)
statement
[...]
Null Statement:
The null statement is merely a semicolon alone.
;
A null statement does not do anything. It does not store a value anywhere.
It does not cause time to pass during the execution of
your program.
Most often, a null statement is used as the body of a loop statement,
or as one or more of the expressions in a for statement. Here is an
example of a for statement that uses the null statement as the body of
the loop (and also calculates the integer square root of n, just for
fun):
for (i = 1; i*i < n; i++)
;
Here is another example that uses the null statement as the body of
a for loop and also produces output:
for (x = 1; x <= 5; printf ("x is now %d\n", x), x++)
;
A null statement is also sometimes used to follow a label that would
otherwise be the last thing in a block.
In your case, the ; is the Null Statement of the for Statement:
int func_prim (int zahl) {
int count;
if (zahl < 0)
return -1;
for (count = 2; zahl % count != 0 && zahl >= count; count++)
;
if (count == zahl)
return 1;
return 0;
}
Without it, the if becomes the for statement:
int func_prim (int zahl) {
int count;
if (zahl < 0)
return -1;
for (count = 2; zahl % count != 0 && zahl >= count; count++)
if (count == zahl)
return 1;
return 0;
}
Therefore, behaving differently.
The for loop is there just to increase the value of count.
a for loop will (normally) have a body,
where the body is enclosed in braces { }
However, for a single statement body, the braces are optional.
; is an empty statement.
Combining the above it becomes obvious that the for loop executes until the condition becomes false.
The for loop is basically looping through all the numbers that are less than or equal to zahl but greater than 2 and storing it in the variable count. As it loops through all these numbers it is checking to see if zahl is divisible by count. If zahl is divisible by count, the loop is stopped. Otherwise, the loop is stopped when count equals zahl.
The if statement after the for loop checks to see if count is equal to zahl. If it is, then that must mean that the loop went through all the numbers less than zahl and greater than 2. This means that zahl is divisible by all the numbers less than itself and greater 2, which makes zahl prime.
It indicates the statement the for loop is used for. It can't be empty. At least it should include a single statement. ; is the empty statement which the iteration is done for.
while ((R_SPI2SR & B_SPIF) != B_SPIF)
{
SERIAL_SERVICE_WDOG;
};
while ((R_SPI2SR & B_SPIF) != B_SPIF)
{
SERIAL_SERVICE_WDOG;
}
I like to know what is the purpose in putting semicolon..
The semicolon after the first loop is not a part of that loop at all. It is interpreted as a completely independent empty statement that sits between the loops. I.e. your actual loops are seen as absolutely identical by C language.
The statement executed by the while loop is the compound statement inside the curly braces. The semicolon is just a gratuitous empty statement. You could have written this loop as:
while ((R_SPI2SR & B_SPIF) != B_SPIF)
SERIAL_SERVICE_WDOG;
since the compound statement just has a single statement inside it, or as
while ((R_SPI2SR & B_SPIF) != B_SPIF)
{
SERIAL_SERVICE_WDOG;;;;;;;;;;;;;;;
};;;;;;;;;;;;;;
which of course is awful style.
An empty statement is used when you have a loop that needs no body.
/* Throw away remaining characters up to the end of line. */
while ( ( c = getchar() ) != '\n')
;
You want to watch out for the classic error of ending a loop prematurely:
int i = 1;
int j = 1;
while ( i < 10 ); /* The semicolon here ends the loop... */
j *= i++; /* ... so this statement is only executed once. */
Unnecessary semicolons are just clutter, so you should never use them.
the only different in the code is the additional semicolon.
but the compiled assembly are the same.