Roquentin
Roquentin

Reputation: 207

How to fix pass by reference not changing values properly

I have a function which is supposed to change a value declared and defined in main. Within the function the pass by reference argument is supposed to be incremented every time a comparison is made. The function is declared like so:

int binSearch (int arr[], int size, int target, int * numComparisons) { ... 
    (*numComparisons)++; }

Within the scope of the function, this is accomplished. However, after the function is finished, the value of numComparisons doesn't actually change. I wrote a printf expression to output the value of numComparisons every iteration of the loop, and it does work properly(it outputs 1, 2, et cetera), however after the function has run the variable passed as an argument to binSearch stays at the value I initialized it to. What is my problem?
(within main)

printf("%d, %d\n", binSearch(testArray, 100, 75, numCompAddress), numCompTest); 
// this returns the index and the incorrect value of numComparisons

Upvotes: 1

Views: 70

Answers (2)

Jean-Baptiste Yunès
Jean-Baptiste Yunès

Reputation: 36401

When calling printf("%d, %d\n", binSearch(testArray, 100, 75, numCompAddress), numCompTest); order of the evaluation of the sub expressions is not defined by the standard which says:

3.4.4

1 unspecified behavior

use of an unspecified value, or other behavior where this International Standard provides two or more possibilities and imposes no further requirements on which is chosen in any instance

2 EXAMPLE An example of unspecified behavior is the order in which the arguments to a function are evaluated.

Looks like in your case, the value of the second argument numCompTest is emitted before the function is called. Change to:

printf("%d, ", binSearch(testArray, 100, 75, numCompAddress));
printf("%d\n", numCompTest);

and you will see what you want.

Upvotes: 4

0___________
0___________

Reputation: 67475

I will always change. The problem is somewhere else (in the code you do not show)

#include <stdio.h>

void foo(int *x)
{
    (*x)++;
}

int main(void) {
    int x = rand();
    printf("Before : %d\n", x);
    foo(&x);
    printf("After : %d\n", x);
    return 0;
}

https://ideone.com/B3zD47

Upvotes: -1

Related Questions