What's the difference in the outcome between call by reference and copy/restore?
Background: I'm currently studying distributed systems. Concerning the passing of reference parameters for remote procedure calls, the book states that: "the call by reference has been replaced by copy/restore. Although this is not always identical, it is good enough". I understand how call by reference and copy/restore work in principle, but I fail to see where a difference in the result may be?
Examples taken from here.
Main code:
#include <stdio.h>
int a;
int main() {
a = 3;
f( 4, &a );
printf("%d\n", a);
return 0;
}
Call by Value:
f(int x, int &y){
// x will be 3 as passed argument
x += a;
// now a is added to x so x will be 6
// but now nothing is done with x anymore
a += 2*y;
// a is still 3 so the result is 11
}
Value is passed in and has no effect on the value of the variable passed in.
Call by Reference:
f(int x, int &y){
// x will be 3 as passed argument
x += a;
// now a is added to x so x will be 6
// but because & is used x is the same as a
// meaning if you change x it will change a
a += 2*y;
// a is now 6 so the result is 14
}
Reference is passed in. Effectively the variable in the function is the same as the one outside.
Call with Copy/Restore:
int a;
void unsafe(int x) {
x= 2; //a is still 1
a= 0; //a is now 0
}//function ends so the value of x is now stored in a -> value of a is now 2
int main() {
a= 1;
unsafe(a); //when this ends the value of a will be 2
printf("%d\n", a); //prints 2
}
Value is passed in and has no effect on the value of the variable passed in UNTIL the end of the function, at which point the FINAL value of the function variable is stored in the passed in variable.
The basic difference between call by reference and copy/restore then is that changes made to the function variable will not show up in the passed in variable until after the end of the function while call by reference changes will be seen immediately.
Call by Copy/Restore is a special case of call-by-reference where the provided reference is unique to the caller. The final result on the referenced values will not be saved until the end of the function.
This type of calling is useful when a method in RPC called by reference. The actual data is sent to the server side and the final result will send to the client. This will reduce the traffic, since the server will not update the reference each time.
Call By Reference:
In call-by-reference, we pass a pointer to the called function. Any changes that happens to the data pointed by that pointer will be reflected immediately.
Suppose if there are numerous changes to be made to that data, while it wouldn’t incur much cost locally, it’ll be expensive in terms of network cost as for each change data will have to be copied back to the client.
C Code:
void addTwo(int *arr, int n){
for(int i=0;i<n;i++){
arr[i]+=2; //change is happening in the original data as well
}
}
int main(){
int arr[100]={1,2,3,...}; // assuming it to be initialised
addTwo(arr,100);
}
Call By Copy/Restore:
In call-by-copy/restore, the idea is that when the function is called with the reference to the data, only the final result of the changes made to the data is copied back to the original data(when the function is about to return) without making any changes to the original data during the function call, requiring only one transfer back to the client.
In the C code below, the data pointed by arr is copied in the function and stored back to arr after all the changes to the local data are finalised.
C Code:
void addTwo(int *arr, int n){
// copy data locally
larr = (int*)malloc(n*sizeof(int));
for(int i=0;i<n;i++){
larr[i]=arr[i];
}
for(int i=0;i<n;i++){
// change is happening to the local variable larr
larr[i]+=2;
}
//copy all the changes made to the local variable back to the original data
for(int i=0;i<n;i++){
arr[i]=larr[i];
}
}
int main(){
int arr[100]={1,2,3,...}; // assuming it to be initialised
addTwo(arr,100);
}
Note: Code shown above doesn’t represent actual RPC implementation, just an illustration of the concepts. In real RPC, complete data is passed in the message instead of pointers(addresses).
Related
I am trying to understand how the concepts of parameter passing by Value Result and parameter passing by Name would apply to the following program:
// GLOBAL variables
int num[10] = {0,0,0,0,0,0,0,0,0,0}; // Subscripts start at 0 as in C++
int index = 1;
void somefun(int alpha, int beta)
{
alpha = 7;
num[index] = 33;
index = index - 6;
num[alpha] = 44;
beta = 55;
}
void main()
{
somefun( index, num[index + 4] ); // Function Call
}
This program is pseudo-code, not specific to any language, and the array subscripts start at 0.
If someone could help me understand how this program would work with parameter passing by Value Result and parameter passing by Name, I would greatly appreciate it. Thank you.
Unfortunately, I was not able to try anything on my own thus far.
I have tried to convert the MQL5 function for simple moving average to OpenCL based kernel program.
Here is what I did:
MQL5 function
void CalculateSimpleMA(int rates_total,int prev_calculated,int begin,const double &price[])
{
int i,limit;
//--- first calculation or number of bars was changed
if(prev_calculated==0)// first calculation
{
limit=InpMAPeriod+begin;
//--- set empty value for first limit bars
for(i=0;i<limit-1;i++) ExtLineBuffer[i]=0.0;
//--- calculate first visible value
double firstValue=0;
for(i=begin;i<limit;i++)
firstValue+=price[i];
firstValue/=InpMAPeriod;
ExtLineBuffer[limit-1]=firstValue;
}
else limit=prev_calculated-1;
//--- main loop
for(i=limit;i<rates_total && !IsStopped();i++)
ExtLineBuffer[i]=ExtLineBuffer[i-1]+(price[i]-price[i-InpMAPeriod])/InpMAPeriod;
//---
}
OpenCL
#pragma OPENCL EXTENSION cl_khr_fp64 : enable
__kernel void CalculateSimpleMA(
int rates_total,
int prev_calculated,
int begin,
int InpMAPeriod,
__global double *price,
__global double *ExtLineBuffer
)
{
int i,limit;
int len_price = get_global_id(4);
if(prev_calculated==0)// first calculation
{
limit=InpMAPeriod+begin;
for(i=0;i<limit-1;i++)
ExtLineBuffer[i]=0.0;
double firstValue=0;
for(i=begin;i<limit;i++)
firstValue+=price[i];
firstValue/=InpMAPeriod;
ExtLineBuffer[limit-1]=firstValue;
}
else limit=prev_calculated-1;
for(i=limit;i<rates_total;i++)
ExtLineBuffer[i]=ExtLineBuffer[i-1]+(price[i]-price[i-InpMAPeriod])/InpMAPeriod;
}
The program is working fine. But the question is I did use OpenCL so that I get to use the multiple cores of the GPU. But what I see is that I am able to consume single core only. While I tried using worker in the Execution, that kernel failed to execute. This is what going on.
I thought that there is some mistake I did while converting the function to Opencl program.
Kindly, suggest me what I missed owing to what nature I am getting through my program. I wanted to use all the cores if possible.
EDITED
The question is related to the conversion of the function from one language to another.
I am using I2C_master library for AVR, Communication works fine, but I have little problem, how can I get data.
I am using this function
uint16_t i2c_2byte_readReg(uint8_t devaddr, uint16_t regaddr, uint8_t* data, uint16_t length){
devaddr += 1;
if (i2c_start(devaddr<<1|0)) return 1;
i2c_write(regaddr >> 8);
i2c_write(regaddr & 0xFF);
if (i2c_start(devaddr<<1| 1)) return 1;
for (uint16_t i = 0; i < (length-1); i++)
{
data[i] = i2c_read_ack();
}
data[(length-1)] = i2c_read_nack();
i2c_stop();
return 0;}
And now I need to use received data, and send it by UART to PC
uint8_t* DevId;
i2c_2byte_readReg(address,REVISION_CODE_DEVID,DevId,2);
deviceH=*DevId++;
deviceL=*DevId;
UART_send(deviceH);
UART_send(deviceL);
I think that I am lost with pointers. Could you help me, how can I get received data for future use? (UART works fine for me in this case, but it sends only 0x00 with this code)
The function i2c_2byte_readReg takes as a third argument a pointer to the buffer where the data will be written. Note that it must have size bigger than the forth argument called length. Your DevId pointer doesn't point to any buffer so when calling the function you've got an access violation.
To get the data you should define an array before calling the function:
const size_t size = 8;
uint8_t data[size];
Then you can call the function passing the address of the buffer as an argument (the name of the array is converted into its address):
const uin16_t length = 2;
i2c_2byte_readReg(address, REVISION_CODE_DEVID, data, length);
Assuming that the function works well those two bytes will be saved into data buffer. Remember that size must be bigger or equal to length argument.
Then you can send the data over UART:
UART_send(data[0]);
UART_send(data[1]);
UPDATE: I solved my problem (scroll down).
I'm writing a small C program and I want to do the following:
The program is connected to a mysql database (that works perfectly) and I want to do something with the data from the database. I get about 20-25 rows per query and I created my own struct, which should contain the information from each row of the query.
So my struct looks like this:
typedef struct {
int timestamp;
double rate;
char* market;
char* currency;
} Rate;
I want to pass an empty array to a function, the function should calculate the size for the array based on the returned number of rows of the query. E.g. there are 20 rows which are returned from a single SQL query, so the array should contain 20 objectes of my Rate struct.
I want something like this:
int main(int argc, char **argv)
{
Rate *rates = ?; // don't know how to initialize it
(void) do_something_with_rates(&rates);
// the size here should be ~20
printf("size of rates: %d", sizeof(rates)/sizeof(Rate));
}
How does the function do_something_with_rates(Rate **rates) have to look like?
EDIT: I did it as Alex said, I made my function return the size of the array as size_t and passed my array to the function as Rate **rates.
In the function you can access and change the values like (*rates)[i].timestamp = 123 for example.
In C, memory is either dynamically or statically allocated.
Something like int fifty_numbers[50] is statically allocated. The size is 50 integers no matter what, so the compiler knows how big the array is in bytes. sizeof(fifty_numbers) will give you 200 bytes here.
Dynamic allocation: int *bunch_of_numbers = malloc(sizeof(int) * varying_size). As you can see, varying_size is not constant, so the compiler can't figure out how big the array is without executing the program. sizeof(bunch_of_numbers) gives you 4 bytes on a 32 bit system, or 8 bytes on a 64 bit system. The only one that know how big the array is would be the programmer. In your case, it's whoever wrote do_something_with_rates(), but you're discarding that information by either not returning it, or taking a size parameter.
It's not clear how do_something_with_rates() was declared exactly, but something like: void do_something_with_rates(Rate **rates) won't work as the function has no idea how big rates is. I recommend something like: void do_something_with_rates(size_t array_size, Rate **rates). At any rate, going by your requirements, it's still a ways away from working. Possible solutions are below:
You need to either return the new array's size:
size_t do_something_with_rates(size_t old_array_size, Rate **rates) {
Rate **new_rates;
*new_rates = malloc(sizeof(Rate) * n); // allocate n Rate objects
// carry out your operation on new_rates
// modifying rates
free(*rates); // releasing the memory taken up by the old array
*rates = *new_rates // make it point to the new array
return n; // returning the new size so that the caller knows
}
int main() {
Rate *rates = malloc(sizeof(Rate) * 20);
size_t new_size = do_something_with_rates(20, &rates);
// now new_size holds the size of the new array, which may or may not be 20
return 0;
}
Or pass in a size parameter for the function to set:
void do_something_with_rates(size_t old_array_size, size_t *new_array_size, Rate **rates) {
Rate **new_rates;
*new_rates = malloc(sizeof(Rate) * n); // allocate n Rate objects
*new_array_size = n; // setting the new size so that the caller knows
// carry out your operation on new_rates
// modifying rates
free(*rates); // releasing the memory taken up by the old array
*rates = *new_rates // make it point to the new array
}
int main() {
Rate *rates = malloc(sizeof(Rate) * 20);
size_t new_size;
do_something_with_rates(20, &new_size, &rates);
// now new_size holds the size of the new array, which may or may not be 20
return 0;
}
Why do I need to pass the old size as a parameter?
void do_something_with_rates(Rate **rates) {
// You don't know what n is. How would you
// know how many rate objects the caller wants
// you to process for any given call to this?
for (size_t i = 0; i < n; ++i)
// carry out your operation on new_rates
}
Everything changes when you have a size parameter:
void do_something_with_rates(size_t size, Rate **rates) {
for (size_t i = 0; i < size; ++i) // Now you know when to stop
// carry out your operation on new_rates
}
This is a very fundamental flaw with your program.
I want to also want the function to change the contents of the array:
size_t do_something_with_rates(size_t old_array_size, Rate **rates) {
Rate **new_rates;
*new_rates = malloc(sizeof(Rate) * n); // allocate n Rate objects
// carry out some operation on new_rates
Rate *array = *new_rates;
for (size_t i = 0; i < n; ++i) {
array[i]->timestamp = time();
// you can see the pattern
}
return n; // returning the new size so that the caller knows
}
sizeof produces a value (or code to produce a value) of the size of a type or the type of an expression at compile time. The size of an expression can therefore not change during the execution of the program. If you want that feature, use a variable, terminal value or a different programming language. Your choice. Whatever. C's better than Java.
char foo[42];
foo has either static storage duration (which is only partially related to the static keyword) or automatic storage duration.
Objects with static storage duration exist from the start of the program to the termination. Those global variables are technically called variables declared at file scope that have static storage duration and internal linkage.
Objects with automatic storage duration exist from the beginning of their initialisation to the return of the function. These are usually on the stack, though they could just as easily be on the graph. They're variables declared at block scope that have automatic storage duration and internal linkage.
In either case, todays compilers will encode 42 into the machine code. I suppose it'd be possible to modify the machine code, though that several thousands of lines you put into that task would be much better invested into storing the size externally (see other answer/s), and this isn't really a C question. If you really want to look into this, the only examples I can think of that change their own machine code are viruses... How are you going to avoid that antivirus heuristic?
Another option is to encode size information into a struct, use a flexible array member and then you can carry both the array and the size around as one allocation. Sorry, this is as close as you'll get to what you want. e.g.
struct T_vector {
size_t size;
T value[];
};
struct T_vector *T_make(struct T_vector **v) {
size_t index = *v ? (*v)->size++ : 0, size = index + 1;
if ((index & size) == 0) {
void *temp = realloc(*v, size * sizeof *(*v)->value);
if (!temp) {
return NULL;
}
*v = temp;
// (*v)->size = size;
*v = 42; // keep reading for a free cookie
}
return (*v)->value + index;
}
#define T_size(v) ((v) == NULL ? 0 : (v)->size)
int main(void) {
struct T_vector *v = NULL; T_size(v) == 0;
{ T *x = T_make(&v); x->value[0]; T_size(v) == 1;
x->y = y->x; }
{ T *y = T_make(&v); x->value[1]; T_size(v) == 2;
y->x = x->y; }
free(v);
}
Disclaimer: I only wrote this as an example; I don't intend to test or maintain it unless the intent of the example suffers drastically. If you want something I've thoroughly tested, use my push_back.
This may seem innocent, yet even with that disclaimer and this upcoming warning I'll likely see a comment along the lines of: Each successive call to make_T may render previously returned pointers invalid... True, and I can't think of much more I could do about that. I would advise calling make_T, modifying the value pointed at by the return value and discarding that pointer, as I've done above (rather explicitly).
Some compilers might even allow you to #define sizeof(x) T_size(x)... I'm joking; don't do this. Do it, mate; it's awesome!
Technically we aren't changing the size of an array here; we're allocating ahead of time and where necessary, reallocating and copying to a larger array. It might seem appealing to abstract allocation away this way in C at times... enjoy :)
i have this work that seems to be like an atm but my problem is i want to update balance but i cant. Say for instance when i first check the balance it gives out "0", then if i deposit "200" when i go to check for the balance again it gives me "200" now then after if i want to withdraw "100" then when i check for the balance it then should give me "100". but i have a problem in passing the values in functions. here is my work. please help me. oh by the way, im using DEV C+
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
// Declaring Functions that exist in the program.
int menu();
// End
// Main method at top, just to help with readability. And it can use the functions since we have already told main they exist.
int main()
{
int a = 0;
int option;
int atmDeposit();
int atmWithdrawal(int balance);
int atmCheck(int z);
system("cls");
do
{
option = menu();
switch(option)
{
case 1:
atmDeposit();
break;
case 2:
atmWithdraw(a);
break;
case 3: atmCheck(a);
break;
case 4:
printf("\nGoodbye!");
system("pause");
exit(0);
default:
printf("\nInvalid!\n");
break;
}
}
while (option != 4);
getch();
return 0;
}
int menu()
{
int op;
system("cls");
printf("What do you want to do?: \n");
printf("1 - Deposit\n");
printf("2 - Withdraw\n");
printf("3 - Check Balance\n");
printf("4 - Exit\n\n");
printf("Enter Choice: ");
scanf("%d",&op);
return op;
}
// End
// to check balance
int atmCheck(int z)
{
printf("\nYour Balance is P%d\n",z);
system("pause");
return z;
}
// End check balance
// to Deposit
int atmDeposit()
{
int deposit, a=0;
printf("\nHow much money do you want to deposit?: P");
scanf("%d", &deposit);
a += deposit;
printf("%d",a);
system("pause");
return a;
}
// end deposit
// to withdraw
int atmWithdraw(int balance)
{
int withdraw;
printf("\nHow much money do you want to withdraw?: P");
scanf("%d", &withdraw);
balance -= withdraw;
printf("%d",balance);
system("pause");
return balance;
}
// end withdraw
There are several things wrong here. First of all, the variables used in your withdrawal and deposit functions are limited in scope to those functions only. Hence, the next time you ask user to submit choice and perform action, the values assigned the last time are lost.
You can rectify this by using the variable a declared in main to store the balance, and then act on it in your other functions. However, if variable is declared in main, which is also a function, it will not be recognised in other functions. So, you need to declare it outside main, like so:
int menu();
int a = 0;
int main()
{
...
}
Next, in your atmDeposit function, you declare a local variable a. When you add the deposit amount to that, the value is retained only in that iteration. The next time you ask user to input a choice, the variable gets reset to 0 and your previous changes are lost. So, get rid of the local variable and use the global variable declared as above. The same fix is required for atmWithdraw and atmCheck functions - subtract the deposit from, and return, the global variable for balance amount.
Finally, I'm not sure why you need an input parameter for any of these functions, since you take input from user for deposit and withdrawal. So, remove the input parameters for functions. Additionally, I'm not sure why you want to return values, if you are only showing the new balance on screen in each case. So your function signatures should like:
void atmDeposit();
void atmWithdraw();
void atmCheck();
1) Declare your variable int a=0; globally (ie; outside the main function - as below). This allows all functions to access the common variable.
int a=0;
int main()
{
...
2) In function int atmDeposit(), remove the declaration a=0; .
3) In function int atmWithdraw(int balance) add the following line before system("pause");
a = balance;
With these changes the program works.