In C, I have a function that calculates the product of a and b. If a < b it returns false otherwise returns true. How can I return the product when the function is defined as boolean?
bool multiplication(int a, int b)
{
int c = a*b;
if (a < b)
return false;
else
return true;
}
How to return bool and double simultaneously?
A function can only have one return type. But you can use a workaround of using a struct containing a bool and an int members as stated in one of the comments.
You can achieve your goal of writing a multiplication function of positive integers with a recursion logic the following way too:
int multiplication(int a, int b) {
if(b <= 1) return a;
return a + multiplication(a, --b);
}
There are a few ways that come to mind that you can use to return a boolean and double simultaneously:
Return the boolean as the return value and return the double as an output parameter.
Return a structure that has the boolean value as one field and the double value as another field.
Return the boolean value as the return value and return the double value using a global variable.
Here's what code for these solutions respectively might look like:
bool multiplication(int a, int b, double* product)
{
*product = a * b;
return a >= b;
}
And:
struct retval {
bool b;
double p;
}
struct retval multiplication(int a, int b)
{
struct retval result;
result.b = a >= b;
result.p = a * b;
return result;
}
And lastly:
double product;
bool multiplication(int a, int b)
{
product = a * b;
return a >= b;
}
Of these, the second solution doesn't fit your question exactly as it no longer returns a bool (but instead returns a struct which can have other downsides in C). The third solution, I despise because I strongly dislike the use of globals (globals make unit testing harder, keeps the using function from being able to be a pure function, causes threading issues).
So this leaves the first solution.
Hope this answers your question.
You can define a new parameter as output.
define a struct included bool and int data.
Initiate the struct, then return it.
Related
#include<stdio.h>
int areaOfRectangle(int,int);
int perimeter(int,int);
int main()
{
int l,b;
scanf(" %d %d",&l,&b);
printf("%d %d %d %d",l,b,areaOfRectangle(l,b),perimeter(l,b));
return 0;
}
int areaOfRectangle(int a,int b)
{
int area;
area=a*b;
return area;
}
int perimeter(int c,int d)
{
int meter;
meter=2(c+d);
return meter;
}
why this error:called object is not a function or function pointer at line: meter=2(c+d)?
Also, can I use the same variable a,b to pass in perimeter function?
Your code meter=2(c+d);should be changes as meter=2*(c+d);
You can use the same variable a,b to pass in perimeter function, A parameter is just a local variable.
In this statement:
int perimeter(int c,int d)
{
int meter;
meter=2(c+d);
return meter;
}
You'll obviously get a syntax error since the compiler won't detect 2(c+d) as you're trying to implicitly multiply 2 with (c + d). Rather, if you explicitly define 2 * (c + d) then it'll no longer show you any error.
One side tip, you don't need to use any local variables inside a function if you just want to return a simple return statement, rather you may use:
return 2 * (c + d);
The declaration is redundant thence.
I want to create a function that performs a function passed by parameter on a set of data. How do you pass a function as a parameter in C?
Declaration
A prototype for a function which takes a function parameter looks like the following:
void func ( void (*f)(int) );
This states that the parameter f will be a pointer to a function which has a void return type and which takes a single int parameter. The following function (print) is an example of a function which could be passed to func as a parameter because it is the proper type:
void print ( int x ) {
printf("%d\n", x);
}
Function Call
When calling a function with a function parameter, the value passed must be a pointer to a function. Use the function's name (without parentheses) for this:
func(print);
would call func, passing the print function to it.
Function Body
As with any parameter, func can now use the parameter's name in the function body to access the value of the parameter. Let's say that func will apply the function it is passed to the numbers 0-4. Consider, first, what the loop would look like to call print directly:
for ( int ctr = 0 ; ctr < 5 ; ctr++ ) {
print(ctr);
}
Since func's parameter declaration says that f is the name for a pointer to the desired function, we recall first that if f is a pointer then *f is the thing that f points to (i.e. the function print in this case). As a result, just replace every occurrence of print in the loop above with *f:
void func ( void (*f)(int) ) {
for ( int ctr = 0 ; ctr < 5 ; ctr++ ) {
(*f)(ctr);
}
}
Source
This question already has the answer for defining function pointers, however they can get very messy, especially if you are going to be passing them around your application. To avoid this unpleasantness I would recommend that you typedef the function pointer into something more readable. For example.
typedef void (*functiontype)();
Declares a function that returns void and takes no arguments. To create a function pointer to this type you can now do:
void dosomething() { }
functiontype func = &dosomething;
func();
For a function that returns an int and takes a char you would do
typedef int (*functiontype2)(char);
and to use it
int dosomethingwithchar(char a) { return 1; }
functiontype2 func2 = &dosomethingwithchar
int result = func2('a');
There are libraries that can help with turning function pointers into nice readable types. The boost function library is great and is well worth the effort!
boost::function<int (char a)> functiontype2;
is so much nicer than the above.
Since C++11 you can use the functional library to do this in a succinct and generic fashion. The syntax is, e.g.,
std::function<bool (int)>
where bool is the return type here of a one-argument function whose first argument is of type int.
I have included an example program below:
// g++ test.cpp --std=c++11
#include <functional>
double Combiner(double a, double b, std::function<double (double,double)> func){
return func(a,b);
}
double Add(double a, double b){
return a+b;
}
double Mult(double a, double b){
return a*b;
}
int main(){
Combiner(12,13,Add);
Combiner(12,13,Mult);
}
Sometimes, though, it is more convenient to use a template function:
// g++ test.cpp --std=c++11
template<class T>
double Combiner(double a, double b, T func){
return func(a,b);
}
double Add(double a, double b){
return a+b;
}
double Mult(double a, double b){
return a*b;
}
int main(){
Combiner(12,13,Add);
Combiner(12,13,Mult);
}
Pass address of a function as parameter to another function as shown below
#include <stdio.h>
void print();
void execute(void());
int main()
{
execute(print); // sends address of print
return 0;
}
void print()
{
printf("Hello!");
}
void execute(void f()) // receive address of print
{
f();
}
Also we can pass function as parameter using function pointer
#include <stdio.h>
void print();
void execute(void (*f)());
int main()
{
execute(&print); // sends address of print
return 0;
}
void print()
{
printf("Hello!");
}
void execute(void (*f)()) // receive address of print
{
f();
}
Functions can be "passed" as function pointers, as per ISO C11 6.7.6.3p8: "A declaration of a parameter as ‘‘function returning type’’ shall be adjusted to ‘‘pointer to function returning type’’, as in 6.3.2.1. ". For example, this:
void foo(int bar(int, int));
is equivalent to this:
void foo(int (*bar)(int, int));
I am gonna explain with a simple example code which takes a compare function as parameter to another sorting function.
Lets say I have a bubble sort function that takes a custom compare function and uses it instead of a fixed if statement.
Compare Function
bool compare(int a, int b) {
return a > b;
}
Now , the Bubble sort that takes another function as its parameter to perform comparison
Bubble sort function
void bubble_sort(int arr[], int n, bool (&cmp)(int a, int b)) {
for (int i = 0;i < n - 1;i++) {
for (int j = 0;j < (n - 1 - i);j++) {
if (cmp(arr[j], arr[j + 1])) {
swap(arr[j], arr[j + 1]);
}
}
}
}
Finally , the main which calls the Bubble sort function by passing the boolean compare function as argument.
int main()
{
int i, n = 10, key = 11;
int arr[10] = { 20, 22, 18, 8, 12, 3, 6, 12, 11, 15 };
bubble_sort(arr, n, compare);
cout<<"Sorted Order"<<endl;
for (int i = 0;i < n;i++) {
cout << arr[i] << " ";
}
}
Output:
Sorted Order
3 6 8 11 12 12 15 18 20 22
You need to pass a function pointer. The syntax is a little cumbersome, but it's really powerful once you get familiar with it.
typedef int function();
function *g(function *f)
{
f();
return f;
}
int main(void)
{
function f;
function *fn = g(f);
fn();
}
int f() { return 0; }
It's not really a function, but it is an localised piece of code. Of course it doesn't pass the code just the result. It won't work if passed to an event dispatcher to be run at a later time (as the result is calculated now and not when the event occurs). But it does localise your code into one place if that is all you are trying to do.
#include <stdio.h>
int IncMultInt(int a, int b)
{
a++;
return a * b;
}
int main(int argc, char *argv[])
{
int a = 5;
int b = 7;
printf("%d * %d = %d\n", a, b, IncMultInt(a, b));
b = 9;
// Create some local code with it's own local variable
printf("%d * %d = %d\n", a, b, ( { int _a = a+1; _a * b; } ) );
return 0;
}
int multiply(int a, char *b)
{
return a b;
}
The code does not execute properly. Try to figure out why.
c program language
Thank your kindhearted help !
the question has been solved simply by me, thank everyone!
int multiply(int a, int b)
{
return a*b;
}
There's more than one error in there.
First, you can't return two variables in the same function, you should return a or the content of the pointer that the variable b in pointing to.
So, you could either use:
return a;
to return the variable a.
or you could use
return *b;
to return the content of the adress that b is pointing to.
If you want to multiply, as the name of the function, you should use:
return a*(*b)
Your function need to return an integer
int multiply(int a, char *b)
but you try to return an int (a) and a char* (b)
if you want to return b (and only b) use
char *multiply(int a, char *b)
You must create a variable that the result will be the multiplication of the parameters and then return the value like the created variable, as I showed.
int multiply (int a, int b) {
int result;
result = a * b;
return(result);
}
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
returning multiple values from a function
Suppose i have passed two values to a function iCalculate(int x, int y) and this iCalculate returns two values. Those are as follows:-
(x*y)
(x/y)
Now how should i return the above two values at the same time with the same function?
My Approach was:-
int* iCalculate(int x,int y){
int temp[2];
temp[0] = x*y;
temp[1] = x/y;
return temp;
}
returning the address of the first element of a local array has undefined behavior(at least dereferencing it later is).
You may use output parameters, that is, pass two pointers, and set the values inside
void Calculate(int x, int y, int* prod, int* quot)
{
*prod = x*y;
*quot = x/y;
}
usage:
int x = 10,y = 2, prod, quot;
Calculate(x, y, &prod, ")
Another thing you could do is pack your data into a struct
typedef struct
{
int prod;
int quot;
} product_and_quot;
product_and_quot Calculate(int x, int y)
{
product_and_quot p = {x*y, x/y};
return p;
}
That won't work, since you're returning a pointer to a temporary array, which will stop existing at function return time.
Instead, define
typedef struct { int first, second; } IntPair;
and return an object of that type.
(This is what the standard library functions div and ldiv do, except that they call the type differently.)
Your approach is wrong, temp is out of scope/ not longer exist when functon iCalculate exit. So you must not return the address of temp. That would be address of out of scope/ no longer exist variable. Accessing that address means undefined behaviour.
You can use this approach:
void iCalculate(int x,int y,int *mult,int *divi){
*mult = x*y;
*divi = x/y;
}
or you can use another approach:
typedef struct{
int mul, divi;
} TResult;
TResult iCalculate(int x,int y){
TResult res;
res.mul = x*y;
res.divi = x/y;
return res;
}
or :
void iCalculate(int x,int y,TResult *res){
res->mul = x*y;
res->divi = x/y;
}
I suggest the first approach. I think it is too silly to create a new struct definition only to wrap 2 unrelated value together.
The way you did is wrong since int temp[2] disappears once the function returns, so the caller has a "dangling" pointer. You have to add static. Another way, likely better, is to let the caller pass where it wants the result be store e.g.
void iCalc(int x, int y, int *rp, int *rq)
{
// check if rp and rq are NULL, if so, returns
*rp = x*y;
*rq = x/y; // y != 0, and this will truncate of course.
}
and the caller will do something like
int res[2];
iCalc(x, y, res, res+1);
or similar.
Your approach was not so wrong you can return the address of the table like this :
int *iCalculate(int x,int y){
int *temp=malloc(sizeof(int)*2);
temp[0]=x*y;
temp[1]=x/y;
return temp;
}
dont forget to free the memory :
int *result;
result=iCalculate(10,7);
printf("%d %d\n",result[0],result[1]);
free(result);
I am trying to calculate the exponent of a number. When I do everything as int I get the correct result, but the output must be float, when I try to convert with %f in printf() I get 0, when I use %d I get the correct result. I cannot change the main() portion of the program, I can only alter the *powerArgs() function. The program input is 3, 5.
Full disclosure, this is part of a school assignment. I am not asking for complete code. I would appreciate a more general answer showing me what I am forgetting, possibly what area I should study more to find the answer myself.
#include <stdio.h>
#include <stdlib.h>
int *powerArgs(int *pA, int *pB);
/* MAIN */
int main(int argc, char **argv)
{
if (argc != 3)
{
printf("?Invalid number of arguments\n");
system("pause");
exit(1);
}
int parmA = atoi(argv[1]);
int parmB = atoi(argv[2]);
int idx;
/* Part C: Raise parmA to the power of parmB. Return pointer to the result */
/* Reset the original values after we print the result */
printf("%d raised to the %d power is %0.1f\n", parmA, parmB, *powerArgs(&parmA, &parmB));
printf("\n");
system("pause");
exit(0);
}
int *powerArgs(int *pA, int *pB)
{
int idx, result = *pA;
for (idx = 1; idx < *pB; idx++)
{
result *= *pA;
}
return &result;
}
float and int convert automatically in C - you can assign either one to the other, and the only thing to watch out for is that if you assign too large a float to an int, then you get undefined behavior (or possibly an unspecified result, I forget. Either way it's not good).
So, your powerArgs function can just be:
float powerArgs(float a, int b) {
// do some stuff and return a value
}
Then you can call it as powerArgs(parmA, parmB), even though parmA is an int.
Edit: if you can't change the call parameters, you can do this instead
float powerArgs(int *a, int *b) {
float base = *a;
int exponent = *b;
...
}
If your professor has really set you code where the function is called as *powerArgs(int *a, int *b), then your professor is a menace. There is no earthly reason why an exponentiation function should return a pointer to a float. There's an ugly workaround you could use:
float *powerArgs(int *a, int *b) {
static float result;
...
result = /* the result of the calculation */;
return &result;
}
The problem with this is, all calls to powerArgs share the same object result. static stops it from ceasing to exist at the end of the call, but the sharing will introduce problems in the long run. It is not good practice to do this, but it might be the best solution to the problem you've been set.
C++ sneaky solution:
struct FloatWrapper {
float value;
float operator*() {
return value;
}
FloatWrapper(float f) : value(f) {}
};
FloatWrapper powerArgs(int *a, int *b) {
...
float result = /* whatever */;
...
return result;
}
This returns an object of class FloatWrapper, by value, and FloatWrapper overloads the * operator. This means that *powerArgs(...) evaluates to the float that the function should have returned by value in the first place, without needing a pointer to any special storage place.
By the way, you might want to check what your function does when parmB is 0.
First, your int *powerArgs(int *pA, int *pB) function returns the address of a local variable, which results in undefined behavior. Use the following instead:
int powerArgs(int *pA, int *pB)
{
int idx, result = *pA;
for (idx = 1; idx < *pB; idx++)
{
result *= *pA;
}
return result;
}
Next, if you want to convert to float, you shouldn't do that in the call to printf(), but rather convert the value to float before the call like so:
printf("%d raised to the %d power is %0.1f\n", parmA, parmB, (float)powerArgs(&parmA, &parmB));
When a function terminates, all its local variables cease to exist (and their addresses point to garbage). To please your teacher who came up with that very awkward interface, you have to find a way to keep an object alive after the function exists.
You have, at least, 3 options:
a) reuse one of the input parameters
b) use a global variable
c) use a static variable
option a)
int *powerArgs(int *pA, int *pB) {
/* calculate */
*pA = CALCULATED_VALUE;
return pA;
}
option b)
int global_power;
int *powerArgs(int *pA, int *pB) {
/* calculate */
global_power = CALCULATED_VALUE;
return &global_power;
}
option c)
int *powerArgs(int *pA, int *pB) {
static int static_power;
/* calculate */
static_power = CALCULATED_VALUE;
return &static_power;
}
Neither of these "solutions" is good; the least bad is option c)