for()循环以及逗号表达式注意事项

for()循环:for(; ;)

第一个表达式不必初始化一个变量,同时,它也可以是某种类型的printf()语句,要记住第一个表达式只在执行循环的其他部分之前被求值或执行一次。

举个例子:

#include

int main()
{
    int n = 1;
    for(printf("welcome to hello world\n");n != 8;)
        scanf("%d",&n);
    printf("that is i wanted\n");


    return 0;
}

执行结果为:

welcome to hello world
1
3
5
66
8
that is i wanted

 

 

逗号表达式注意:

逗号运算符,优先级别最低,把两个表达式链接为一个表达式,并保证左边的表达式最先计算,它通常被用在for循环的控制表达式中,以包含多个信息,整个表达式的值为最后一个表达式的值。

例如:i = (10,20); i最后的值为20.

作为顺序点的逗号保证左边子表达式的副作用在计算右边子表达式之前生效。

测试代码如下:

#include


int main()
{
    int first = 37;
    int second = 23;
    double cost = 0;
    int count = 0;
    for(count = 1,cost = first;count <= 10;++count,cost += second)
    {
        printf("count  %d, cost is $%0.2f\n",count,cost / 100.0);
    }

    
    return 0;
}

结果如下:

count  1, cost is $0.37
count  2, cost is $0.60
count  3, cost is $0.83
count  4, cost is $1.06
count  5, cost is $1.29
count  6, cost is $1.52
count  7, cost is $1.75
count  8, cost is $1.98
count  9, cost is $2.21
count  10, cost is $2.44

 

你可能感兴趣的:(学习笔记)