View Full Version : C++ Pass by value overwritten?

09-03-2009, 08:16 PM
I am trying to figure out why my value isn't being passed to my main function.

void passValue(int a[], int n, int executionCount)
for(int i = 1; i < n; i++)

while(i < n; i++)

int main()
int n = 20;
int *a = (int*) calloc(n, sizeof(int));

int executionCount = 0;


passValue(a, n, executionCount);

for(int i = 0; i < n; i++)
txtFile << a[i] << " ";

txtFile << "\n" << "Executions: " << executionCount;

I removed most of the non-trivial code.

when printing, executionCount = 0 while in the passValue() function, it registers a different value, the one that should be printed.. also how can i calculate the time it takes for the passValue function to execute?

09-03-2009, 08:40 PM
You need to pass the executionCount variable by reference if you want the changed value in passValue to change the variable in main. Pass by value makes a copy so the variable in the passValue function has a different memory location than the one in main.

09-03-2009, 09:02 PM
I changed to pass by reference, so that seems to work, but also how can i calculate the time it takes for the passValue function to execute?Since this is going to be a very quick time im assuming it may be best to use tickcounts? or is there a better way to accurately find the time of this function execution time

09-03-2009, 11:19 PM
Please note that for you code, unless you have a very large value of n, you'll get wildly varying times. Note also that other activities on the computer will also affect the times.

This code provides milliseconds for my logging system. If you have a decent system with no other users, you may get good results from changing it to microseconds ( unsigned long microseconds=((m_stop.tv_sec-m_start.tv_sec)*1000000)+(m_stop.tv_usec-m_start.tv_usec); ) but I strongly suggest doing a few million iterations for more reliable measurements.

#include <sys/time.h>
#include <time.h>

timeval m_start;
timeval m_stop;

//do your thing
unsigned long milliseconds=((m_stop.tv_sec-m_start.tv_sec)*1000)+((m_stop.tv_usec-m_start.tv_usec)/1000);

EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum