我的问题一般与函数调用有关,但我想到了 当我使用堆编写优先级队列时。只是为了提供一些上下文(不是很重要),我的堆从上到下从左到右存储项目,我将堆表示为结构数组。插入新项目后,我只是将其放在堆中的最后一个位置,然后调用底部的函数“fix_up”,它将将该项目移动到堆中的正确位置。我想知道如果不是做...
fix_up(pQueue->heap, pQueue->size);
pQueue->size++;
...我可以做...
fix_up(pQueue->heap, pQueue->size++);
出于几个原因,我不确定这是否可行。
1) 由于 pQueue->size 在函数调用中,我什至不确定它实际上是 pQueue->size 还是存储在 pQueue->size 中的整数的副本。如果它是一个副本,那么显然我不会将 1 添加到实际的 pQueue->size 中,所以这样做没有意义。
2) 因为它是一个函数调用,所以它会进入函数 fix_up 并执行那里的所有代码。我想知道这是否会产生意想不到的后果,即当它进入 fix_up 时,它会增加 1,并且我的索引会比我在执行 fix_up 时的预期高 1?或者它会做它应该做的事情并等到 fix_up 完成执行之后?
3) 即使没问题,它是否被认为是 C 语言的良好编码习惯?
Status priority_queue_insert(PRIORITY_QUEUE hQueue, int priority_level, int data_item)
{
Priority_queue *pQueue = (Priority_queue*)hQueue;
Item *temp_heap;
int i;
/*Resize if necessary*/
if (pQueue->size >= pQueue->capacity) {
temp_heap = (Item*)malloc(sizeof(Item) * pQueue->capacity * 2);
if (temp_heap == NULL)
return FAILURE;
for (i = 0; i < pQueue->size; i++)
temp_heap[i] = pQueue->heap[i];
pQueue->capacity *= 2;
}
/*Either resizing was not necessary or it successfully resized*/
pQueue->heap[pQueue->size].key = priority_level;
pQueue->heap[pQueue->size].data = data_item;
/*Now it is placed as the last item in the heap. Fixup as necessary*/
fix_up(pQueue->heap, pQueue->size);
pQueue->size++;
//continue writing function code here
}
最佳答案
是的,你可以。
但是,您不能这样做:
foo(myStruct->size++, myStruct->size)
原因是 C 标准没有说明参数的计算顺序。这会导致未定义的行为。
1) Since pQueue->size is in the function call, I'm not even sure if it's actually pQueue->size or rather a copy of the integer stored in pQueue->size. If it was a copy then obviously I wouldn't be adding 1 to the actual pQueue->size so there'd be no point in doing this.
无论您向函数发送什么参数,它都会在函数开始执行之前进行评估。所以
T var = expr;
foo(var);
总是等同于
foo(expr);
2) Since it's a function call, it is going to then go into the function fix_up and execute all the code there. I am wondering if this would have an unintended consequence of maybe when it went to fix_up it would get incremented by 1 and my index would be 1 higher than I intended while executing fix_up? Or would it do what it's supposed to do and wait until after fix_up had finished executing?
见上文
3) Even if it is ok, is it considered a good coding practice for C?
有点主观,对于这个网站来说有点过时,但我还是会从我个人的角度回答这个问题。一般来说,我会尽量避免它。
关于可以在函数调用的参数中使用后增量运算符吗?在C?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58743339/