C의 전체 "for"루프 구문은 무엇입니까?
for
다른 사람의 코드를 읽을 때 매우 이상한 루프를 보았습니다 . for
루프 인에 대한 전체 구문 설명을 검색하려고 C
했지만 " for
" 라는 단어 가 관련없는 문장에 나타나기 때문에 Google에서 검색을 거의 불가능하게하기 때문에 매우 어렵습니다 .
이 글 을 읽은 후이 질문이 떠 올랐 습니다.
for
여기 :
for(p=0;p+=(a&1)*b,a!=1;a>>=1,b<<=1);
중간 조건에서 두 코드를 구분하는 쉼표가 있습니다.이 쉼표는 무엇을합니까? 오른쪽의 쉼표는 a>>=1
및 b<<=1
.
그러나 루프 종료 조건 내에서 어떤 일이 발생합니까? 언제 p==0
, 언제 a==1
또는 둘 다 발생 하면 종료됩니까 ?
누군가가 이것을 이해하도록 도와주고 전체 for
루프 구문 설명 의 방향을 알려줄 수 있다면 좋을 것 입니다.
쉼표는 for 루프를 제외하지 않습니다. 쉼표 연산자입니다.
x = (a, b);
먼저 a를 수행 한 다음 b를 수행 한 다음 x를 b 값으로 설정합니다.
for 구문은 다음과 같습니다.
for (init; condition; increment)
...
어느 정도 (무시 continue
하고 break
지금은) 다음과 같습니다.
init;
while (condition) {
...
increment;
}
따라서 for 루프 예제는 (다시 무시 continue
하고 break
)
p=0;
while (p+=(a&1)*b,a!=1) {
...
a>>=1,b<<=1;
}
마치 (다시 무시 continue
하고 break
) 것처럼 작동합니다 .
p=0;
while (true) {
p+=(a&1)*b;
if (a == 1) break;
...
a>>=1;
b<<=1;
}
위의 while 루프로의 단순화 된 변환에없는 for 루프의 두 가지 추가 세부 사항 :
- 조건이 생략되면, 그것은 항상
true
(A 않는 무한 루프의 결과로break
,goto
또는 뭔가 다른 휴식 루프). - A
continue
는 증분continue
을 건너 뛰는 while 루프 와 달리 증분 직전의 레이블로 이동하는 것처럼 작동합니다 .
또한 쉼표 연산자에 대한 중요한 세부 정보 : &&
and와 같은 시퀀스 포인트입니다 ||
(이 때문에 별도의 문으로 분할하고 의미를 그대로 유지할 수 있습니다).
C99의 변경 사항
C99 표준은이 설명의 앞부분에서 언급되지 않은 몇 가지 뉘앙스를 도입합니다 (C89 / C90에 매우 적합).
첫째, 모든 루프는 그 자체로 블록입니다. 효과적으로,
for (...) { ... }
그 자체가 한 쌍의 중괄호로 싸여 있습니다.
{
for (...) { ... }
}
표준은 다음과 같이 말합니다.
ISO / IEC 9899 : 1999 §6.8.5 반복 문
¶5 An iteration statement is a block whose scope is a strict subset of the scope of its enclosing block. The loop body is also a block whose scope is a strict subset of the scope of the iteration statement.
This is also described in the Rationale in terms of the extra set of braces.
Secondly, the init
portion in C99 can be a (single) declaration, as in
for (int i = 0; i < sizeof(something); i++) { ... }
Now the 'block wrapped around the loop' comes into its own; it explains why the variable i
cannot be accessed outside the loop. You can declare more than one variable, but they must all be of the same type:
for (int i = 0, j = sizeof(something); i < j; i++, j--) { ... }
The standard sayeth:
ISO/IEC 9899:1999 §6.8.5.3 The for statement
The statement
for ( clause-1 ; expression-2 ; expression-3 ) statement
behaves as follows: The expression expression-2 is the controlling expression that is evaluated before each execution of the loop body. The expression expression-3 is evaluated as a void expression after each execution of the loop body. If clause-1 is a declaration, the scope of any variables it declares is the remainder of the declaration and the entire loop, including the other two expressions; it is reached in the order of execution before the first evaluation of the controlling expression. If clause-1 is an expression, it is evaluated as a void expression before the first evaluation of the controlling expression.133)
Both clause-1 and expression-3 can be omitted. An omitted expression-2 is replaced by a nonzero constant.
133) Thus, clause-1 specifies initialization for the loop, possibly declaring one or more variables for use in the loop; the controlling expression, expression-2, specifies an evaluation made before each iteration, such that execution of the loop continues until the expression compares equal to 0; and expression-3 specifies an operation (such as incrementing) that is performed after each iteration.
The comma simply separates two expressions and is valid anywhere in C where a normal expression is allowed. These are executed in order from left to right. The value of the rightmost expression is the value of the overall expression.
for
loops consist of three parts, any of which may also be empty; one (the first) is executed at the beginning, and one (the third) at the end of each iteration. These parts usually initialize and increment a counter, respectively; but they may do anything.
The second part is a test that is executed at the beginning of each execution. If the test yields false
, the loop is aborted. That's all there is to it.
The C style for loop consists of three expressions:
for (initializer; condition; counter) statement_or_statement_block;
- The initializer runs once, when the loop starts.
- The condition is checked before each iteration. The loop runs as long it evaluates to true.
- The counter runs once after each iteration.
Each of these parts can be an expression valid in the language you write the loop in. That means they can be used more creatively. Anything you want to do beforehand can go into the initializer, anything you want to do in between can go into the condition or the counter, up to the point where the loop has no body anymore.
To achieve that, the comma operator comes in very handy. It allows you to chain expressions together to form a single new expression. Most of the time it is used that way in a for loop, the other implications of the comma operator (e.g. value assignment considerations) play a minor role.
Even though you can do clever things by using syntax creatively - I would stay clear of it until I find a really good reason to do so. Playing code golf with for loops makes code harder to read and understand (and maintain).
The wikipedia has a nice article on the for loop as well.
Everything is optional in a for
loop. We can initialize more than one variable, we can check for more than one condition, we can iterate more than one variable using the comma operator.
The following for
loop will take you into an infinite loop. Be careful by checking the condition.
for(;;)
Konrad mentioned the key point that I'd like to repeat: The value of the rightmost expression is the value of the overall expression.
A Gnu compiler stated this warning when I put two tests in the "condition" section of the for loop
warning: left-hand operand of comma expression has no effect
What I really intended for the "condition" was two tests with an "&&" between. Per Konrad's statement, only the test on to the right of the comma would affect the condition.
the for loop is execution for particular time for(;;)
the syntex for for loop
for(;;)
OR
for (initializer; condition; counter)
e.g (rmv=1;rmv<=15;rmv++)
execution to 15 times in for block
1.first initializ the value because start the value
(e.g)rmv=1 or rmv=2
2.second statement is test the condition is true or false ,the condition true no.of time execution the for loop and the condition is false terminate for block,
e.g i=5;i<=10 the condition is true
i=10;i<10 the condition is false terminate for block,
3.third is increment or decrement
(e.g)rmv++ or ++rmv
참고URL : https://stackoverflow.com/questions/276512/what-is-the-full-for-loop-syntax-in-c
'programing tip' 카테고리의 다른 글
Json을 Asp.Net Web API의 파생 형식으로 역 직렬화 (0) | 2020.12.07 |
---|---|
ember-cli 0.0.47 업그레이드 후 콘텐츠 보안 정책 지침 위반 (0) | 2020.12.07 |
iPhone SDK :보기 내에서 비디오를 재생하는 방법은 무엇입니까? (0) | 2020.12.07 |
Java-URL의 리디렉션 된 URL을 찾는 방법은 무엇입니까? (0) | 2020.12.07 |
TRUNCATE와 DELETE FROM의 장단점 (0) | 2020.12.07 |