Given the two code examples which is preferred? In the first the return variable is defined as a local variable. In the second the return variable is passed by the caller. Are you allowed to define a function and return a variable that was passed to it? I's this simply a preference of one or the other? is there a performance difference?
float compute_diam(float circumference, float pi) {
float rval;
/* Circumference = pi * diameter, so
diameter = circumference / pi */
rval = circumference / pi;
return rval;
}
and
float compute_diam(float circumference, float pi, float rval) {
/* Circumference = pi * diameter, so
diameter = circumference / pi */
rval = circumference / pi;
return rval;
}
Thanks
I think in these two cases the 1st one is better for following reason
1. Due to performance as you are passing variable by value it is once created where ever you declare rval, and once when you pass that rval to function with value of first rval copied to second.
instead if you want to pass variable in this manner pass it by reference as
void main()
{
float result;
compute_diam(2.1, 3.14, &result);
}
void compute_diam(float circumference, float pi, float* rval) {
/* Circumference = pi * diameter, so
diameter = circumference / pi */
*rval = circumference / pi;
}
after completion of the function variable result will hold the value of diameter.
Sometime you may want to pass the reference of the variable and then fill it will appropriate value or return codes.
However the second definition does not make any sense.
int foo()
{
int a=6;
return a; // This is ok
}
int foo(int a)
{
a = 5;
return a; // Calling function cant access the value 5 in the parameter
//passed, it has to hold it in another variable
}
void foo(int* a)
{
*a=5;
return; // Here you can return and still access the value 5 in the calling
//function with the variable passed to it
}
Hence i am assuming you want to decide between first and third method and i would say its implementation specific. If you want to pass a sequence of return values(read array,structures) you can use the second.
I'd prefer the first as the second doesn't make any sense. The second you're not passing in a reference or a pointer to the rval so you're just assigning to a local variable (as you are in the first, yet it's created differently) and then returning a copy of that variable to the caller. Note that you're not saving the value in the rval passed TO the function, you're saving it in the local rval created BY the function via the parameter list.
Even if the second example was passing a reference to rval, I would still prefer the first as rval is a regular type and is easily and efficiently copied. I also find:
float diameter = compute_diam(circumference, pi);
much more readable and concise than:
float diameter = 0;
compute_diam(circumference, pi, diameter);
If you were putting data into a large object/struct, then passing a reference into the function would make more sense. A compiler many times can optimize out the copy associated with a function that incurs a copy for the return value, so I would probably stay with option 1 until you find through the use of a profiler that it needs to be optimized to something like the 2nd version.
Also, you could remove pi from the argument list and make a static const float PI = 3.14xxxx; inside the function body.
Typically, the only reasons to store the return value at an address passed as a parameter are:
You need to return multiple values.
You need to return a structure.
You need to use the return value of the function to return errors.
The function is designed to modify one of the parameters.
If you look through the standard C library, or most any API, you'll find few instances of return values stored at an address passed as a parameter.
This let me think that you don't understand what a return value is or how arguments are given to a function.
In your second example, you will not modify the rval that you are giving at function call, but a copy of it. And you will then return the value of rval.
Your second example is then "wrong" (from a logic point of view).
What you were trying to do is
void compute_diam(float circumference, float pi, float& rval) {
/* Circumference = pi * diameter, so
diameter = circumference / pi */
rval = circumference / pi;
}
Edit: Correction, the above is only C++, in C you would do the following
void compute_diam(float circumference, float pi, float* rval) {
/* Circumference = pi * diameter, so
diameter = circumference / pi */
*rval = circumference / pi;
}
Where rval is given by reference and where the function doesn't return anything (void).
But this should be avoided in that simple case, the interface is more clear if the function return a value.
Edit:
To convince you that your second example is ill formed, think about the following:
float my_result = compute_diam(2.0, 3.14, 'why and what would I put here ? my_result ? ')
Related
I am working on C implementations of calculus operations (such as derivatives, integrals, etc...). As an example, here's the template definition of my derivative function:
double derivative(double (*f)(double), double x);
Let's say I want to compute the derivative of exp at 1, the call would then be: derivative(exp, 1);
Pretty basic stuff. Now my question is, how would I go about (if it is even possible) to pass a composition to my derivative function? I tried passing exp(cos) which got me
error: passing 'double (double)' to parameter of incompatible type 'double'.
How would I do it? Is it even possible?
I think you're asking for this:
double composition(double x) {
return exp(cos(x));
}
derivative(composition, 1);
Many languages allow you to do something like the following, but C doesn't have anon functions:
derivative(x => exp(cos(x)), 1);
If you want some sort of run-time control over the composition, you could write a function that evaluates an array of function pointers as a composition:
// calls functions in reverse order
double compose(size_t n, double (* const fc[])(double), double x)
{
while (n--)
{
x = fc[n](x);
}
return x;
}
This could be called from another version of your derivative function:
double derivative_composed(size_t n, double (* const fc[])(double), double x)
{
// Example implementation for illustrative purpose only.
double fx, fxh, h;
h = x / 1e10;
if (h == 0)
{
h = 1e-10;
}
fx = compose(n, fc, x);
fxh = compose(n, fc, x + h);
return (fxh - fx) / h;
}
To avoid repeated code, your original derivative function could be changed to be a wrapper that calls derivative_composed with a single function:
double derivative(double (* const f), double x)
{
return derivative_composed(1, &f, x);
}
Example usage:
int main(void)
{
double (* const fc[2])(double) = { exp, cos };
double x = 1.0;
double xprime = derivative_composed(2, fc, x);
printf("x = %f, xprime = %f\n", x, xprime);
}
Output:
x = 1.000000, xprime = -1.444407
C does not have any operation for function composition. To compute the derivative of exp∘cos, you can define a function expcos:
double expcos(double x)
{
return exp(cos(x));
}
and take the derivative of that.
For a more general solution, you could modify your derivative routine to take both a function pointer and a const void * to forward to the function. The function would take the const void * as a parameter, convert it to a pointer to a const structure of a type particular to that function, and take data from that structure. Then function composition can be implemented with a compose function that uses a structure containing two function pointers. However, it would mean you would need to use proxy routines for ordinary functions like exp and cos that accept but ignore the const void *.
I would like to pass a pointer as an argument into a function that normalizes the vector pointer that was passed as an argument.
Here are the functions:
float norm(Vector *v) {
float len;
len = sqrt(pow(v->x, 2.0) + pow(v->y, 2.0) + pow(v->z, 2.0));
return len;
}
Vector normalize(Vector *vec){
Vector normVec;
//calls norm function which also takes a pointer of vector type as argument
float norm = norm(&vec);
normVec.x = vec->x/norm;
normVec.y = vec->y/norm;
normVec.z = vec->z/norm;
return normVec;
}
I get this error:
error: called object ‘norm’ is not a function or function pointer.
How can I get this function running smoothly?
That is because your float norm variable shadows the norm() function.
Name one of them something else.
Also, vec is already a pointer, no need to take its address (&vec) when you pass it to norm()
I have recently stumbled on this curious thought while handling a C code.
I have written a function which returns a double and takes in as argument the pointer to a function and a certain number of parameters, namely
double template_1(double (*)(double),...);
this function correctly identifies a certain property of a real function
double f(double );
represented as a pointer in template_1, in order to maketemplate_1 valid for every real function I might plug-in.
Now I had to write another function, let it be:
double derivative(double (*)(double),double);
double derivative(double (*f)(double),double x){
double epsilon = ...;
return ( f(x+epsilon)-f(x-epsilon) )/(2.0*epsilon);
}
again with f in the argument to make it work for every f.
My question is: since I would like to use derivative in template_1 without modifying it, is it possible to write a function which takes derivative and spits out something that has the form of double (*)(double ) ?
My idea was to define typedef double (*real_function)(double);
and then to define
real_function g(double (*derivative)(double (*)(double),double ) )
which I'd like it to spit out something like: double derivative_2(double x); so that I could define something like g(derivative) = double (*h)( double); directly in template_1 argument
unfortunately I don't have the faintest idea of how to make this work, or even if it can work.
There are a couple ways to do anonymous functions in C. As the comments said, they aren't portable. But depending on the use case you may find this useful: Anonymous functions using GCC statement expressions
A couple of people have seemed to have similar issues, not sure how portable they are but they may be resourceful:
https://github.com/graphitemaster/lambdapp
https://github.com/Leushenko/C99-Lambda
Basically, if there's a way to architect your program in a way that doesn't require anonymous functions, then do it that way. If you have no other option, then I would give one of these a shot.
Warning: I am a C++ developer with little C knowledge so everything that follows is likely unidiomatic C.
As KerrekSB said, you would need to carry some state with your function. This is not possible with raw functions but you can define a struct that carries the state and add a function that works with this struct. This obviously has the drawback of losing the nice function call syntax. I whipped up an example:
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
typedef double (*raw_fptr)(double);
struct real_function;
typedef double (*evaluate_function)(struct real_function*, double);
struct real_function {
evaluate_function evaluate;
};
typedef struct real_function real_function;
double evaluate(real_function *f, double x) {
if(f) {
return f->evaluate(f, x);
}
return NAN;
}
struct raw_real_function {
real_function real_function_base;
raw_fptr raw_function;
};
typedef struct raw_real_function raw_real_function;
double evaluate_raw_real_function(real_function *f_base, double x) {
if(f_base) {
raw_real_function *f = (raw_real_function*)f_base;
return f->raw_function(x);
}
return NAN;
}
raw_real_function make_raw_real_function(raw_fptr function) {
raw_real_function result;
result.raw_function = function;
result.real_function_base.evaluate = evaluate_raw_real_function;
return result;
}
struct derive_real_function {
real_function real_function_base;
real_function *function_to_derive;
};
typedef struct derive_real_function derive_real_function;
double derive(real_function *f_base, double x) {
derive_real_function *f = (derive_real_function*)f_base;
double epsilon = 1e-3;
double upper = evaluate(f->function_to_derive, x+epsilon);
double lower = evaluate(f->function_to_derive, x-epsilon);
double result = (upper - lower)/(2.0*epsilon);
return result;
}
derive_real_function make_derivative(real_function * function_to_derive) {
derive_real_function result;
result.real_function_base.evaluate = derive;
result.function_to_derive = function_to_derive;
return result;
}
double x_cubed(double x) {
return x * x * x;
}
int main(int argc, char **argv) {
raw_real_function x_cubed_wrapped = make_raw_real_function(x_cubed);
derive_real_function derived = make_derivative(&x_cubed_wrapped.real_function_base);
derive_real_function derived_twice = make_derivative(&derived.real_function_base);
double x = atof(argv[1]);
double derivative = evaluate(&derived.real_function_base, x);
double second_derivative = evaluate(&derived_twice.real_function_base, x);
printf("derivative of x^3 at %f = %f\n", x, derivative);
printf("second derivative of x^3 at %f = %f\n", x, second_derivative);
return 0;
}
See (a slight variaton, due to input limitations) running here.
How does it work? I faked some inheritance with the structs real_function, raw_real_function and derive_real_function to generate virtual function calls. The struct real_function serves as the container of a virtual function table consisting of only the entry evaluate. This function pointer points to the "derived" structs' relevant evaluate function:
raw_real_function instances point to evaluate_raw_real_function (as initialized in make_raw_real_function. derive_real_function instances point evaluate to derive (as initialized in make_derivative).
When calling evaluate on the real_function_base member, it will call the associated evaluation function, which casts the real_function* to it's associated struct pointer and does what is needed with that information.
Since everything is just a real_function*, we can chain them at will but need to convert "normal" functions into the real_function format, that's what make_raw_real_function does.
If you have a function my_fancy_function:
double my_fancy_function (double x) { return sin(x) + cos(x); }
Then, you can use a helper macro that creates the derived function for you.
#define DEFINE_DERIVATIVE_OF(FUNC) \
double derivative_of_ ## FUNC (double x) { \
return derivative(FUNC, x); \
}
DEFINE_DERIVATIVE_OF(my_fancy_function)
You then pass this newly defined function to your template.
template_1(derivative_of_my_fancy_function, x, y, z);
I am working on a problem in my textbook and I need to make a triangle angle calculator Im used to java but Im not 100% on C yet, I don't understand the logic in it.
#include <stdio.h>
static float angleB;
static float angleA;
float remainingAngle(float answer)
{
float answer= angleA+angleB;
//redefinition of answer
return 0;
}
//CANT TOUCH FROM HERE TO END
int main(int argc, const char * argv[]) {
float angleA = 30.0;
float angleB = 60.0;
float angleC = remainingAngle(angleA,angleB);
// to many arguments to function call (referring to angleC)
printf("the third angle is %.2f\n",angleC);
return 0;
} //END CANT TOUCH
I don't know what to do here.
In your function definition
float remainingAngle(float answer)
the function remainingAngle() accepts one parameter.
OTOH, in your function call
remainingAngle(angleA,angleB);
you're passing two arguments.
The supplied argument number and type should match with the parameter list in function definition.
That said, your code is wrong.
Point 1. Your local variables will shadow the global ones. Maybe that's not what you want. Change
float angleA = 30.0;
float angleB = 60.0;
to
angleA = 30.0;
angleB = 60.0;
Point 2. The function
float remainingAngle(float answer)
{
float answer= angleA+angleB;
//redefinition of answer
return 0;
}
is logically wrong. It should rather be
float remainingAngle(void)
{
float answer= angleA+angleB;
return answer;
}
and should be called like
float angleC = remainingAngle();
AFTER EDIT:
as per your requirement, you can do
float remainingAngle(float angleA, float angleB)
{
float answer= angleA+angleB;
return answer;
}
However, this makes the global variables useless.
In addition to Souravs answer you could also do the following:
float remainingAngle(float angA, float angB)
{
float answer = angA + angB;
return answer;
}
So your call will stay the same.
And for the logical side, what you do is:
You pass two arguments (value of angleA and value of angleB) to the function remainingAngle. There you do the calculation and return the result (answer).
The design of your function isn't good:
static float angleB;
static float angleA;
float remainingAngle(float answer)
{
float answer= angleA+angleB;
//redefinition of answer
return 0;
}
What do I do?
There's no point is passing in the answer; the answer is what you want to receive. (There's also no point in passing "space" for the answer. The anser is a float, a scalar variable. Just pass that around.) Remove the answer argument.
You redefine answer as local variable. After removing the argument of the same name, that redefinition goes away. But in that case you should return answer instead of 0. You could even do without the intermediary variable answer and return the result expression. So: Return the desired expression
The answer depends on two global variables. The function should work on two angles that you pass as arguments. Provide two angle arguments to your function and remove the global variables.
And finally, the sum of the three angles in a triangle is 180°, so your remaining angle calculation is wrong.
Putting all that together:
float remainingAngle(float a, float b)
{
return 180.0f - a - b;
}
and call it like this:
float angleC = remainingAngle(angleA, angleB);
Im used to java
I'm not too familiar with Java, but I don't think functios on scalars like this one are fundamentally different in C and Java.
I'm just making a mess out of this. I have a function that is supposed to take a one-dimensional array, do some calculations with its values, and then return a similar array with the results of the calculation. I don't necessarily care whether it returns the same array (with new values) or if it creates a new array at a different memory location and returns that. Here is what I've got at the moment. There are errors all over this, but I don't know what I am doing wrong. Can anyone help?
double s = 10;
double b = 2.6666;
double r = 28;
double (*newVertex(double vtx[3] )) [] {
static double newVtx[3];
/* Coordinates */
double x = vtx[0];
double y = vtx[1];
double z = vtx[2];
double dt = 0.001;
double dx = s*(y-x);
double dy = x*(r-z)-y;
double dz = x*y - b*z;
newVtx[0] = x + dt*dx;
newVtx[1] = y + dt*dy;
newVtx[2] = z + dt*dz;
return &newVtx;
}
int main(int argc, char *argv[]) {
int i;
/* Arrays to hold the coordinates */
double thisPt[3] = {1, 1, 1};
double nextPt[3];
for (i=0;i<1000;i++) {
printf("%5d %8.3f %8.3f %8.3f\n", i, thisPt[0], thisPt[1], thisPt[2]);
nextPt = newVertex(&thisPt);
thisPt = nextPt;
}
return 0;
}
First of all, your function declaration looks unnecessarily complex to me.
If you're not planning to create a new array, then it should be something like:
void function_name(double *parameter) {
// code to change the parameter in place here
}
or, if you want to be explicit about the length of the array (see comments for additional info):
#define ARRAY_SIZE 3
void function_name(double parameter[ARRAY_SIZE]) {
// code to change the parameter in place here
}
If you're planning to create a new array, then you could do something like:
double * function_name(double *parameter) {
double *result = (double *)malloc(sizeof(double * number_of_elements));
// read parameter, write into result
return result;
}
The above snippet assumes the number_of_elements is fixed and known. If it is not, then you need to handle them as additional arguments.
Next, this is bad for several reasons:
double (*newVertex(double vtx[3] )) [] {
static double newVtx[3];
// update newVtx
return &newVtx;
}
The return statement returns the address of a local variable. In this particular case, the variable is static, so the variable won't be overwritten once the function exits. But does it really need to be static in the first place? And is it sufficient for it to be static? Think about code like this:
double *v1 = newVertex(old_vertex);
double *v2 = newVertex(old_vertex);
You may be tempted to think you can handle the two vertices individually, but they're pointing to the exact same spot in memory: the location of the static variable. It's much more common practice to allocate space for the array dynamically (malloc, calloc) and return a pointer to the allocated memory.
Here nextPt = newVertex(&thisPt);
just pass array name
newVertex(thisPt); //array name thispt==&thispt[0]
thisPt = nextPt; //illegal and remove this line
Your function
void newVertex(double *); //declaration
void newVertex(double *vtx) //defination
{
//donot return array
}
print after function call
newVertex(thisPt);
printf("%5d %8.3f %8.3f %8.3f\n", i, thisPt[0], thisPt[1], thisPt[2]);