简体   繁体   English

C编程语言中的运算符优先级

[英]operator precedence in C programming language

If I write the code like this below? 如果我在下面编写这样的代码?

int arr[] = {6, 7, 8, 9, 10};
int *ptr = arr;
*(ptr++)+= 123;

what's the elements in the arr[] now? 现在arr []中的元素是什么?

I originally thougt the arr[] now should be {6, 130, 8, 9, 10}, but actully the result is {129, 7, 8, 9, 10}, I don't know why? 我本来应该将arr []现在设置为{6,130,8,9,10},但是实际结果是{129,7,8,8,9,10},我不知道为什么?

In my opinion, ptr++ is in the bracket, so the ptr should increase first, isn't it? 我认为,ptr ++放在了括号内,因此应该首先增加ptr,不是吗? after it increased one, it should point to the second element in the array. 增加一个后,它应该指向数组中的第二个元素。

The value of ptr++ is the value of ptr before any increment ( the side-effect is incrementing ptr at some time during the evaluation of the expression ). ptr++的值是任何增量之前的ptr值( 副作用是在表达式计算期间的某个时候增加ptr )。

That is the value that is dereferenced in *(ptr++) . 那是*(ptr++)取消引用的值。

If you dereference ptr in a subsequent expression, it points to the next element, the one with value 7 . 如果在后续表达式中取消引用ptr ,则它指向下一个元素,即值为7元素。

Use ++ptr (ie pre-increment) if you want the behaviour you're expecting. 如果您想要预期的行为,请使用++ptr (即预增量)。 Parentheses don't affect when the post-increment occurs. 后加括号时不影响。 In other words, it's nothing to do with precedence. 换句话说,它与优先级无关。

The basic meaning of ptr++ is First use then Increment that is why it is know as Post Increment Operator . ptr ++的基本含义是先使用Increment然后使用Increment ,这就是为什么它被称为Post Increment Operator It means that the value of the variable ptr will be updated only when the current instruction has finished execution and the variable is used again in subsequent instructions. 这意味着仅当当前指令完成执行并且在后续指令中再次使用该变量时,才会更新变量ptr的值。

While just the opposite applies for ++ptr is First Increment then use and it is known as Pre Increment Operator . 对于++ ptr适用的情况恰好相反,它是First Increment然后使用 ,它被称为Pre Increment Operator

The effect of this ptr++ will take place only after ';' 此ptr ++的效果仅在';'之后出现 ptr++ is equivalent to ptr = ptr + 1; ptr ++等效于ptr = ptr + 1; but this will done only after semicolon of that statement. 但这只能在该语句的分号之后进行。 ptr value will be arr[0] during the operation *(ptr++)+= 123; 在操作*(ptr ++)+ = 123时,ptr值将为arr [0]; but after that statement ptr will be equivalent to arr[1] 但在该语句之后,ptr等同于arr [1]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM