一、递增 (++) 递减(–)
1.何时生效
副作用:在计算表达式时,对变量进行修改
顺序点:在程序执行过程中的一个点,在这里,进行下一步之前将确保对所有的副作用进行了评估。(;以及完整表达式)
e1
while ( i++ <10 )
printf("%d \n", i);
i++ <10是一个完整表达式,副作用在printf()之前完成。i 同10比较后,加1.
e2
y = (4 + x++) + (6 + x++);
分号标明了顺序点,程序值只保证,在执行下一条语句之前,x递增两次。
C++没有规定是在计算每个子表达式之后将x的值递增,还是整个表达式计算完毕后才将x的值递增。应避免这样的使用方式。
2. 指针的递增、递减
double arr[5] ={1, 2, 3, 4, 5};
Rule:
1.前缀递增、前缀递减、解引用操作符的优先级相同。从右往左进行。
2.后缀递增、后缀递减的优先级相同,但比前缀操作符的优先级高。从左往右进行
e1
*++p;
1.++
2.*
结果为arr[1],即2;
e2
++*p;
1.*
2.++
结果为arr[0]+1,即2;
e3
(*p)++;
1.*
2.++
结果为arr[0]+1,即2;
扫描二维码关注公众号,回复:
9014944 查看本文章
e4
*p++;
1.++
2.*
结果为arr[1],即2;
二、字符串比较
**错误示例
char word[5] = "mate";
word == "mate";
word是数组名。不能判断两个字符串是否相同,比较的是他们存储的地址是否相同。
strcmp()比较函数:
str1 str2 可以为char数组或string类
strcmpy(str1, str2)== 0 相等
strcmpy(str1, str2)=!0 不相等
strcmpy(str1, str2)<0 str1在str2前面
strcmpy(str1, str2)>0 str1在str2后面
char数组的比较
char word[10];
strcmp(word, "done");
string类的比较
string word;
word == "done";
三、延时循环
#include <iostream>
#include <cstring>
int main()
{
using namespace std;
cout << "Enter the delay time, in seconds: ";
float secs;
cin >> secs;
clock_t delay = secs * CLOCKS_PER_SEC;
cout << "starting\a\n";
clock_t start = clock();
while (clock() - start < delay)
;
cout << "done!\n";
return 0;
}