I would like to write something like this;
for (op1 in (plus, minus, times, divby, exponent)) {
printf("%d", a op1 b);
}
so that what actually ends up being executed is something like this
printf("%d", a + b);
printf("%d", a - b);
printf("%d", a * b);
printf("%d", a / b);
printf("%d", a ^ b);
How can I write this?
Since you've not posted any code, I'm not going to write any, but will be happy to help with some concepts which you can turn into working code.
Write functions to perform individual operations (addition, subtraction, multiplication etc).
Take an array of function pointers, initialize that with individual functions you want to perform.
Loop over the array and pass the required variables to the function call to get desired output.
Something like (pseudo-code)
funcptr arr[SIZE] = { func1, func2, func3... };
for (int i = 0; i < SIZE ; i++) {
printf("%d\n", arr[i](a, b));
}
That said, just a note, a ^ b is not an "exponent" operator in C, as you might have expected. It is bitwise XOR. You can make use of pow() to get that done.
FYI, you can refer to this question for related information.
Array of function pointers would do.
double plus(int a, int b);
double minus(int a, int b);
double times(int a, int b);
double divby(int a, int b);
double exponent(int a, int b);
typedef double (*p_fun)(int a, int b);
int main()
{
int a = 5, b = 10;
p_fun pa[] = {plus, minus, times, divby, exponent};
for( int i = 0; i < sizeof(pa)/sizeof(p_fun); i++ )
{
printf("%f\n", pa[i](a, b));
}
return 0;
}
Related
void f(int a, char b, char* c) {
if(..) {
...
f(a,b,c); //recursive
}
...
}
void g(int a, double b, char* c, int d) {
if(..) {
...
g(a,b,c,d); //recursive
}
...
}
I want to make a separate function because I use the code within the if statement several times. But this function have to have a function as a parameter becuase I use recursive method. I know that we can use function as a parameters, but in the f function there are 3 parameters, in the g function have 4 parameters.
The code in the if statement in f is the same as the code in the if of g. Except for the function call in that code?
Simply I have no idea how to solve this issue.
You can use union to pack the variable number of arguments, as shown in sample code below.
It may be unusual to use union like this, but it works.
#include<stdio.h>
union u {
struct { int a; char b; char* c; } f;
struct { int a; double b; char* c; int d; } g;
};
void func_u_f (union u* ua) {
printf(" f = {a: %d, b: %c, c:%s}\n", ua->f.a, ua->f.b, ua->f.c);
ua->f.a++;
}
void func_u_g (union u* ua) {
printf(" g = {a: %d, b: %e, c:%s, d:%d}\n",
ua->g.a, ua->g.b, ua->g.c, ua->g.d);
ua->g.a++; ua->g.b *= 2.0; ua->g.d++;
}
void r (int i, void (*func) (union u*), union u* ua) {
if (i < 3) { /* or whatever conditions to terminate recursion */
printf ("Recursion %d\n", i);
func(ua);
r (++i, func, ua);
} else {
printf ("Exit recursion at %d\n", i);
return;
}
}
int main () {
union u u1, u2;
/* f */
u1.f.a = 10; u1.f.b = 'X'; u1.f.c = "I am u.f.";
r(0, &func_u_f, &u1);
/* g */
u2.g.a = 10; u2.g.b = .4e-6; u2.g.c = "I am u.g."; u2.g.d = 98;
r(-2, &func_u_g, &u2);
return 0;
}
I am proposing you an easy fix that doesn't work in general because it involves the use of a sentinel value.
Let's say that the the variable d that you pass to g is always positive. Than you can choose -1 as sentinel value.
You always pass four parameters to the function myIf and then check whether d is -1. If it is, then you call f with three parameters, otherwise you call g.
int main() {
myIf(a, b, c, d);
return 0;
}
void myIf(int a, int b, char *c, int d)
{
if( d == -1 ) {
f(a, b, c);
}
else {
g(a, b, c, d);
}
}
I'm not sure exactly what you're trying to do. But if you're worried about code duplication in the if statements, you can refactor that our to another function:
if (isCondition()) ...
bool isCondition() { return ... }
I'm trying to multiply (3, 6) and (9, 9) using recursion. However, the result printed is 18 and 45. I need to find out which part is wrong.
Here's my code:
#include <stdio.h>
int multiply (int, int);
int main()
{
int a, b, c;
a = 6; b = 3; c = multiply(a, b);
printf("%d\n", c);
a = 9; b = 9; c = multiply(a, b);
printf("%d\n", c);
return 0;
}
int multiply(int a, int b)
{
static int c = 0, i = 0;
if (i < a) {
c = c + b;
i++;
multiply(a, b);
}
return c;
}
The issue is that multiply's static variables persist from call to call, which throws the second calculation off. It is possible to bandage this wound, but it's better to address the underlying design problem that is compelling use of static variables in the first place. There is no need to artificially maintain state in the function using i (the number of additions to perform) and c (a product accumulator).
Given that multiplication is repeated addition of a b times, you can establish a base case of b == 0 and recursively add a, incrementing or decrementing b (depending on b's sign) until it reaches 0. The product accumulator c is replaced by the function return value and the number of multiplications i is represented by b.
Using this approach, each stack frame's state is naturally self-reliant.
#include <stdio.h>
int multiply(int a, int b) {
if (b > 0) {
return a + multiply(a, b - 1);
}
else if (b < 0) {
return -a + multiply(a, b + 1);
}
return 0;
}
int main() {
printf("%d\n", multiply(3, 6));
printf("%d\n", multiply(9, 9));
printf("%d\n", multiply(-6, 2));
printf("%d\n", multiply(6, -2));
printf("%d\n", multiply(-7, -3));
printf("%d\n", multiply(0, 7));
printf("%d\n", multiply(7, 0));
printf("%d\n", multiply(0, 0));
return 0;
}
Output:
18
81
-12
-12
21
0
0
0
As a final note, I recommend following proper code style. Minifying your code and using single-character variable names only makes debugging more difficult (someone has since de-minified the original code in an edit).
Both c and i need to be reset to zero on each [outer] call to multiply [as others have mentioned] because a function scope static variable is only initialized once.
There is no way to do this because the static variables are at multiply function scope (i.e. how does main access/reset them?). They would need to be moved to global/file scope.
Adding a helper function and moving the variables to global scope will do it:
#include <stdio.h>
int multiply(int, int);
int
main()
{
int a,
b,
c;
a = 6;
b = 3;
c = multiply(a, b);
printf("%d\n", c);
a = 9;
b = 9;
c = multiply(a, b);
printf("%d\n", c);
return 0;
}
static int c, i;
int
mul(int a, int b)
{
if (i < a) {
c = c + b;
i++;
mul(a, b);
}
return c;
}
int
multiply(int a, int b)
{
i = 0;
c = 0;
return mul(a,b);
}
Try resetting your static variables before second call to multiply or do without them
int multiply(int a, int b) {
If (a==0)
return 1;
else if (a>0)
return b+multiply(a-1, b);
else
return - 1*multiply(-1*a, b); }
I am working on a simple in-place fourier transform. But I do not know how does the in-place take place. For example the following code snippet, taken from https://rosettacode.org/wiki/Fast_Fourier_transform#C
As the function declares void fft(cplx buf[], int n), without any output, how could the change in buf in the sub-function transfer back into the main function?
#include <stdio.h>
#include <math.h>
#include <complex.h>
double PI;
typedef double complex cplx;
void _fft(cplx buf[], cplx out[], int n, int step)
{
if (step < n) {
_fft(out, buf, n, step * 2);
_fft(out + step, buf + step, n, step * 2);
for (int i = 0; i < n; i += 2 * step) {
cplx t = cexp(-I * PI * i / n) * out[i + step];
buf[i / 2] = out[i] + t;
buf[(i + n)/2] = out[i] - t;
}
}
}
void fft(cplx buf[], int n)
{
cplx out[n];
for (int i = 0; i < n; i++) out[i] = buf[i];
_fft(buf, out, n, 1);
}
void show(const char * s, cplx buf[]) {
printf("%s", s);
for (int i = 0; i < 8; i++)
if (!cimag(buf[i]))
printf("%g ", creal(buf[i]));
else
printf("(%g, %g) ", creal(buf[i]), cimag(buf[i]));
}
int main()
{
PI = atan2(1, 1) * 4;
cplx buf[] = {1, 1, 1, 1, 0, 0, 0, 0};
show("Data: ", buf);
fft(buf, 8);
show("\nFFT : ", buf);
return 0;
}
I am not sure whether I have made the question clear. I wrote a snippet below, with just the same structure with the one above. However, it does not work in in-place mode, by which I mean, the value changes of variable in the sub-function did not transfer into the main function.
#include <stdio.h>
void _sumab(int a, int b, int c)
{
printf("2: %d, %d, %d\n", a, b, c );
a = 2*a + b+c;
b = 12;
// if(a<800) _sumab(a, b, c);
printf("3: %d, %d, %d\n", a, b, c );
}
void sumab(int a, int b, int c)
{
printf("1: %d, %d, %d\n", a, b, c );
_sumab(a, b, c);
a = a*4;
printf("4: %d, %d, %d\n", a, b, c);
}
int main()
{
int out1 = 0;
int out2 = 1;
int out3 = 2;
sumab(out1+100, out2, out3);
printf("5: %d, %d, %d\n", out1, out2, out3);
return 0;
}
in the former code, after calling the sub-function, the value stored in buf changes, even in the main function. but in the latter code, after calling the sub-function, the values of a, b, c remain the same, as they are in the main function scope. Why?
Did I left some important issue or something else? How does the in-place take place?
and if fft(buf, 8) means calculate the fourier transform of buf and store it still in buf, how about the expression fft(buf+2, 8), it will calculate the fourier transform of buf+2, but stores in where?
Thanks in advance.
The key to your question is that in C, you can't pass an array to a function.
When you write this:
void fft(cplx buf[], int n)
The types in that declaration are adjusted * according to the rules defined in §6.7.6.3 p7 of the C11 standard (citing the latest public draft, n1570, here):
A declaration of a parameter as ‘‘array of type’’ shall be adjusted to ‘‘qualified pointer to
type’’, where the type qualifiers (if any) are those specified within the [ and ] of the
array type derivation. [...]
This means, the real declaration looks like this:
void fft(cplx *buf, int n)
So, you're actually passing a pointer and the function can manipulate the original array through that pointer.
*) It's often said the array decays as a pointer. This is not the official wording of the standard, but widely understood. If you have an array like this:
char a[5];
and you just write a, this is evaluated as a pointer to the first element of a, of type char *. So, with a function declared like this:
void foo(char x[]);
you can just call it like
foo(a);
and what really gets passed is the pointer to the first element of a, therefore, a "decays" as a pointer.
#include <stdio.h>
int Add(int a, int b);
int Add(int a, int b, int c);
double Add(double a, double b);
void main()
{
printf("1+2=%d\n",Add(1,2));
printf("3+4+5=%d\n",Add(3,4,5));
printf("1.414+2.54=%f\n",Add(1.414,2.54));
}
int Add(int a, int b)
{
return a+b;
}
int Add(int a, int b, int c)
{
return a+b+c;
}
double Add(double a, double b)
{
return a+b;
}
I wrote with C language and using Xcode. While studying "overload", Xcode keeps show error message that overload cannot be worked. Instead it shows "Conflicting types for 'Add'" message.
With Xcode, would overload cannot be worked?
In Simple words, C doesn't allow function overloading! So, you can't write multiple functions with the same name!
Try to give different function name and try-
#include <stdio.h>
int Add2int(int a, int b);
int Add3int(int a, int b, int c);
double Add(double a, double b);
void main()
{
printf("1+2=%d\n",Add2int(1,2));
printf("3+4+5=%d\n",Add3int(3,4,5));
printf("1.414+2.54=%f\n",Add(1.414,2.54));
}
int Add2int(int a, int b)
{
return a+b;
}
int Add3int(int a, int b, int c)
{
return a+b+c;
}
double Add(double a, double b)
{
return a+b;
}
As mentioned C doesn't support function overloading (like in C++). Neverthless C99 introduced function-like macros with empty arguments, however commas must be preserved with exact number. Here is an example:
#include <stdio.h>
#define Add(a,b,c) (a+0)+(b+0)+(c+0)
int main(void)
{
int a = 1, b = 2, c = 3;
double x = 1.5, y = 2.25, z = 3.15;
printf("%d\n", Add(a, b, c)); /* 6 */
printf("%d\n", Add(a, b, )); /* 3 */
printf("%d\n", Add(, , c)); /* 3 */
printf("%g\n", Add(, y, z)); /* 5.4 */
printf("%g\n", Add(x, , )); /* 1.5 */
return 0;
}
Note that due to due usual arithmetic conversions for arguments with floating-point type 0 would be properly promoted to such type.
This may be only possible if you are using C++.
But in C you can't think of function overloading.
So try to change the function name and then it will work.
Actually C language does not allow function or method overloading
To do method overloading you have to go to C++ or Java
How can I create a "function pointer" (and (for example) the function has parameters) in C?
http://www.newty.de/fpt/index.html
typedef int (*MathFunc)(int, int);
int Add (int a, int b) {
printf ("Add %d %d\n", a, b);
return a + b; }
int Subtract (int a, int b) {
printf ("Subtract %d %d\n", a, b);
return a - b; }
int Perform (int a, int b, MathFunc f) {
return f (a, b); }
int main() {
printf ("(10 + 2) - 6 = %d\n",
Perform (Perform(10, 2, Add), 6, Subtract));
return 0; }
typedef int (*funcptr)(int a, float b);
funcptr x = some_func;
int a = 3;
float b = 4.3;
x(a, b);
I found this site helpful when I was first diving into function pointers.
http://www.newty.de/fpt/index.html
First declare a function pointer:
typedef int (*Pfunct)(int x, int y);
Almost the same as a function prototype.
But now all you've created is a type of function pointer (with typedef).
So now you create a function pointer of that type:
Pfunct myFunction;
Pfunct myFunction2;
Now assign function addresses to those, and you can use them like they're functions:
int add(int a, int b){
return a + b;
}
int subtract(int a, int b){
return a - b;
}
. . .
myFunction = add;
myFunction2 = subtract;
. . .
int a = 4;
int b = 6;
printf("%d\n", myFunction(a, myFunction2(b, a)));
Function pointers are great fun.
You can also define functions that return pointers to functions:
int (*f(int x))(double y);
f is a function that takes a single int parameter and returns a pointer to a function that takes a double parameter and returns int.