c++ 自增运算和指针的优先级问题

reference

i++先赋值再运算;++i先运算再赋值

 

q=*p++;   //等价于 q=*p; p++;

q=*(p++);   //等价于 q=*p; p++;

*和++的优先级是相同的,运算符的结合都是自右向左的,因此 ++只对 p 产生作用,而不是*p

 

https://blog.csdn.net/jingjingaibiancheng/article/details/88653026

https://blog.csdn.net/nanfeibuyi/article/details/80834983

example 1

#include <iostream>
using namespace std;
int main() {
 char blocks[3] = {'A', 'F', 'X'};
 char *ptr = blocks;
 cout << *++ptr << endl;
 cout << ++*ptr << endl;  // address do not change; only the content change 取了值之后,已经和指针没有关系了
 cout << (*ptr)++ << endl; // address do not change; only the content change 取了值之后,已经和指针没有关系了
 cout << *ptr << endl;
 for (int i = 0; i < 3; i++)
cout << "Final blocks[i] is: " << blocks[i] << endl;
 return 0;
}

// F
// G
// G
// H
// Final blocks[i] is: A
// Final blocks[i] is: H
// Final blocks[i] is: X

example 2

#include <iostream>
using namespace std;
int main() {
 char blocks[3] = {'A', 'F', 'X'};
 char *ptr = blocks;
 cout << *++ptr << endl; // F
 cout << ++*ptr << endl; // G  取了值之后,已经和指针没有关系了
 cout << *ptr++ << endl; // G  ptr先赋值 然后ptr再加1(所以地址加1)
 cout << *ptr << endl;
 for (int i = 0; i < 3; i++)
cout << "Final blocks[i] is: " << blocks[i] << endl;
 return 0;
}


F
G
G
X
Final blocks[i] is: A
Final blocks[i] is: G
Final blocks[i] is: X

example 3


#include<iostream>
using namespace std;
int main() {
	int a[4] = {1,3,9};
	int *p=a;

	// cout << "*p:" << *p << endl;  // 1
	// cout << "*p++:" << *p++ << endl; // 1  p先赋值 然后p再加1(所以地址加1)
    // cout << "*p++:" << *p << endl;  // 3

	cout << "*p:" << *p << endl;  // 1
	cout << "*p++:" << (*p)++ << endl; // 1  还是先赋值 再加1  但是此处取了值之后,已经和指针没有关系了
    cout << "*p++:" << *p << endl;  // 2

	// cout << "*p:" << *p << endl;  // 1
	// cout << "*p++:" << *++p << endl; // 3 地址先加1 再赋值
    // cout << "*p++:" << *p << endl;  // 3


	return 0;
}

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值