C语言查遗补缺——关于自增运算符的有趣的例子
只是找了一些例子并运行,没有总结出个规律来,想不清楚内部机制,大家一起给总结一下吧~
首先是跟宏定义结合,这是笔试题中可能遇到的题目,然后展开讨论,关于后自增在逻辑运算符和加法运算符中的区别,但是没有总结出规律,也不明白本质上怎么破。。欢迎大家留言给予指导~
[cpp]
#define BAND1(x) (((x) >= 5)&&((x) <= 10) ? (x) : 0)
#define BAND2(x) (((x) >= 5)&&((x) <= 5) ? (x) : 0)
int main()
{
int a;
int i = 5;
printf("\ntest1----->>>>>>>>>>>>\n");
printf("BAND1(++i) = %d\n", BAND1(++i)); //8
printf("i = %d\n", i); //8
i = 5;
printf("\ntest2----->>>>>>>>>>>>\n");
printf("BAND1(i++) = %d\n", BAND1(i++)); //7
printf("i = %d\n", i); //8
i = 5;
printf("\ntest3----->>>>>>>>>>>>\n");
printf("BAND2(++i) = %d\n", BAND2(++i)); //0
printf("i = %d\n", i); //7
/*说明在((x) >= 5)&&((x) <= 5)部分执行了两次自增 */
i = 5;
printf("\ntest4----->>>>>>>>>>>>\n");
printf("BAND2(i++) = %d\n", BAND2(i++)); //0
printf("i = %d\n", i); //7
/*说明在((x) >= 5)&&((x) <= 5)部分执行了两次自增 */
i = 0;
a = (i++) + (i++) + (i++);
printf("\ntest5----->>>>>>>>>>>>\n");
printf("a = %d\n", a); //0
printf("i = %d\n", i); //3
/*问题是在条件运算符内部就自增了,可是加法时就没有自增,自增操作的时机是?*/
i = 4;
a = (i++ >= 5);
printf("\ntest6----->>>>>>>>>>>>\n");
printf("a = %d\n", a); //0
printf("i = %d\n", i); //5
/*说明在(i++ >= 5)部分没有自增,比较完后才自增 */
i = 4;
a = (i++ >= 5)+(i++ >= 5);
printf("\ntest7----->>>>>>>>>>>>\n");
printf("a = %d\n", a); //1
printf("i = %d\n", i); //6
/*说明在第一个(i++ >= 5)之后,第二个(i++ >= 5)之前自增, 再执行加法*/
i = 4;
a = (i++ >= 4)&&(i++ >= 5);
printf("\ntest8----->>>>>>>>>>>>\n");
printf("a = %d\n", a); //1
printf("i = %d\n", i); //6
/*说明在(i++ >= 4)之后,(i++ >= 5)之前自增, 再执行逻辑运算*/
i = 1;
a = (i--)&&(i);
printf("\ntest9----->>>>>>>>>>>>\n");
printf("a = %d\n", a); //0
printf("i = %d\n", i); //0
/*说明在(i--)之后,i之前自减,再执行逻辑运算*/
i = 1;
a = (i)&&(i--);
printf("\ntest10----->>>>>>>>>>>>\n");
printf("a = %d\n", a); //1
printf("i = %d\n", i); //0
/*说明在(i)之后,i--之前没有自减,再执行逻辑运算*/
#define BAND1(x) (((x) >= 5)&&((x) <= 10) ? (x) : 0)
#define BAND2(x) (((x) >= 5)&&((x) <= 5) ? (x) : 0)
int main()
{
int a;
int i = 5;
printf("\ntest1----->>>>>>>>>>>>\n");
printf("BAND1(++i) = %d\n", BAND1(++i)); //8
printf("i = %d\n", i); //8
i = 5;
printf("\ntest2----->>>>>>>>>>>>\n");
printf("BAND1(i++) = %d\n", BAND1(i++)); //7
printf("i = %d\n", i); //8
i = 5;
printf("\ntest3----->>>>>>>>>>>>\n");
printf("BAND2(++i) = %d\n", BAND2(++i)); //0
printf("i = %d\n", i); //7
/*说明在((x) >= 5)&&((x) <= 5)部分执行了两次自增 */
i = 5;
printf("\ntest4----->>>>>>>>>>>>\n");
printf("BAND2(i++) = %d\n", BAND2(i++)); //0
printf("i = %d\n", i); //7
/*说明在((x) >= 5)&&((x) <= 5)部分执行了两次自增 */
i = 0;
&nb
补充:软件开发 , C语言 ,