C语言之递增运算符(++)与递减运算符(--)

(increment operator)递增运算符(++),(decremen operator)递减运算符(--),的应用范围很广,很多的编程语言都有该内容,(increment operator)递增运算符(++),就是将其运算对象递增加一,而(decremen operator)递减运算符(--)则反之。这两种运算符都有两种方式,其一:(++)或者(--)出现在作用变量前面,例如:--a,++a。其二:(++)或者(--)出现在作用变量的后面,例如:a--,a++。前者称为前缀模式,后者称为后缀模式,那么它们之间又是如何运行工作的呢?请看下面的文章内容。

代码案例一:

#include <stdio.h>
#include <stdlib.h>
#define MXA 100

/* run this program using the console pauser or add your own getch, system("pause") or input loop */

int main(void) {
	int count = MXA + 1;
	
	while(--count > 0){
		printf("%d bottles of spring water on the wall.""%d bottles of spring water!\n",count,count);
		printf("Take one down and pass it around,\n");
		printf("%d bottles of spring water!\n",count - 1);
	}
	
	return 0;
}

运行结果:

代码案例二:

#include <stdio.h>
#include <stdlib.h>
#define MXA 100

/* run this program using the console pauser or add your own getch, system("pause") or input loop */

int main(void) {
	int count = MXA + 1;
	
	while(count-- > 0){
		printf("%d bottles of spring water on the wall.""%d bottles of spring water!\n",count,count);
		printf("Take one down and pass it around,\n");
		printf("%d bottles of spring water!\n",count - 1);
	}
	
	return 0;
}

 运行结果:

在如上的代码案例中可以看出, 它们的运行结果,是一样的,如反过来的话,++count,count++的原理也是一样的,那么写到此处,就得表明:到底是++count先运行还是count++先运行,那么举个简单的例子吧!C = a * ++b;这个是一个前缀形式,是b先加一再乘a,想到此处大致就想到了优先级的知识了。那么C = a * b++;这个则是后缀形式,是a*b赋值给C,b再加1。那么下面再以代码举个例子,如下案例:

代码案例三:

#include <stdio.h>
#include <stdlib.h>
#define MXA 100

/* run this program using the console pauser or add your own getch, system("pause") or input loop */

int main(void) {
	int a = 2,b = 3,c;
	c = a*++b;
	
	printf("c = %d\n",c);
	
	return 0;
}

运行结果:

代码案例四:

#include <stdio.h>
#include <stdlib.h>
#define MXA 100

/* run this program using the console pauser or add your own getch, system("pause") or input loop */

int main(void) {
	int sun = 0;
	
	while(sun++ < 20){
		printf("sun = %d\n",sun);
	} 
	return 0;
}

运行结果:

上面的这几个案例中,不难看出,在平时看别人的代码或者自身写程序的时候常常看到或者用到。 

发布了122 篇原创文章 · 获赞 36 · 访问量 6万+

猜你喜欢

转载自blog.csdn.net/qqj3066574300/article/details/104341456