[英]I declared an i variable inside for loop. But I can't print it outside for loop. So i is like a local variable inside for loop?
#include<stdio.h>
void alldivisor(int n){
for (int i=1; i*i<n; i++) {
if (n%i==0) {
printf("%d ",i);
}
}
printf("\n%d",i);
}
int main(){
int n;
printf("Enter a num: ");
scanf("%d",&n);
alldivisor(n);
}
Yes, i
is a local variable inside the loop.是的, i
是循环内的局部变量。
Try:尝试:
#include <stdio.h>
void alldivisor(int n){
int i = 1;
for (; i*i<n; i++) {
if ((n % i) == 0) {
printf("%d ",i);
}
}
printf("\n%d",i);
}
int main(){
int n;
printf("Enter a num: ");
scanf("%d",&n);
alldivisor(n);
}
A clear understanding in C should be that any variables declared inside the curly braces {}
is inside the scope of the of braces.在 C 中明确的理解应该是在花括号{}
内声明的任何变量都在大括号的 scope 内。 Accessing it somehow using memory address tricks after leaving the scope is UNDEFINED BEHAVIOUR .离开 scope 后,使用 memory 地址技巧以某种方式访问它是UNDEFINED BEHAVIOR 。
Tricks like these is undefined, for example, so do not try them ever:例如,这些技巧是未定义的,所以永远不要尝试它们:
...
int *ptr = NULL;
{
int a = 1;
ptr = &a;
}
/* Accessing address of 'a' is undefined behaviour */
printf("%d\n", *ptr);
...
So, you must define the variable i
inside the scope of the function alldivisor()
;因此,您必须在 function alldivisor()
的 scope 中定义变量i
;
Also, you might see things like:此外,您可能会看到以下内容:
...
for (int i = 0; i < x; i++)
/* one operation */
...
It is a shorthand when you only need to execute one operation for each time in the loop.当您只需要在循环中每次执行一个操作时,它是一种简写。 It also creates a new scope even though curly braces are missing.即使缺少花括号,它也会创建一个新的 scope。
Important thing is that two scopes are created for for
loops, one for the entire loop, hence you can access i
, another for the body, hence you cannot access any declarations inside the body of the loop in the condition box.重要的是,为for
循环创建了两个范围,一个用于整个循环,因此您可以访问i
,另一个用于主体,因此您无法在条件框中访问循环主体内的任何声明。
You must define the variable i
in the scope of the alldivisor()
function:您必须在alldivisor()
function 的 scope 中定义变量i
:
#include<stdio.h>
void alldivisor(int n)
{
/* The variable "i" must be defined in the global scope of the "alldivisor()"*/
int i;
for(i = 1 ; i * i < n; i++)
{
if(n % i == 0)
{
printf("%d ",i);
}
}
printf("\nResult: %d",i);
}
int main()
{
int n;
printf("Enter a num: ");
scanf("%d",&n);
alldivisor(n);
return 0;
}
for ( init-clause; cond-expression; iteration-expression ) loop-statement for ( init 子句; cond 表达式; 迭代表达式 ) 循环语句
As with all other selection and iteration statements, the for statement establishes block scope: any identifier introduced in the init-clause, cond-expression, or iteration-expression goes out of scope after the loop-statement .与所有其他选择和迭代语句一样, for 语句建立块 scope:在 init 子句、cond 表达式或迭代表达式中引入的任何标识符在循环语句之后从 scope 中消失。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.