When and why should I use void as the return type of a function in C? - arrays

I'm currently practising C and learning pointers and arrays. I watched a tutorial where the instructor changed the function from int aFunction() to void aFunction(). Of course, he didn't say why — that's why I'm here. So I'm wondering: when and why should someone use void as the return type for a function.

In C, you have to tell the compiler what are each of the types of the variables you declare. That is why you have things like int and char*.
And functions’ return values are no different. Compiler has to know what each of your functions return types are to work properly. Now if you have a function like add(int a, int b) typically you would want its return type to be of integer, that is why you would define it as
int add(int a, int b)
{
return a+b;
}
Now consider you have a function that doesn’t return anything at all, now you need to tell your compiler that this function returns nothing. That is why void is used. You use void when the function does something but in the end doesn’t need to return any value to the program it was called from. Like this one:
void printAdd(int a, int b)
{
printf(“a + b = %d”, a+b);
}
We are doing a bunch of stuff here but the result from the addition is not returned or stored but rather printed to the screen.
You can use the first function add() like this:
int abc = add(5, 7);
// abc is 12
while you can only use the second function like
printAdd(5, 7);
// you cannot store the value because nothing is returned.
// 5 + 7 = 12 is printed to the screen

The token(s) that precedes the function name in the function declaration is the type of the value that the function returns. In this case there is just one token, but type names may consist of multiple tokens. When you want to return an integer object, you can specify the return type to be int. When the function won't return anything, you use void return type.

Related

How can I implement a function lookup table in C?

Say I had a program where the user could select a number between 0-10. Each number would then correspond to the calling of a certain function. In Python, I know I could just create an array of function names, index into it with the selected option, and then call the function. How would I implement this in C? Or is it even possible?
Here is an example how to do it. Please note that all functions must have the same signature, but of course you can change that from my funptr type to for example a function that has void return or takes a char and not two ints.
// Declare the type of function pointers.
// Here a function that takes two ints and returns an int.
typedef int (*funptr)(int, int);
// These are the two functions that shall be callable.
int f1(int a, int b) { return a + b; }
int f2(int a, int b) { return a - b; }
// The array with all the functions.
funptr functions[] = {
f1,
f2,
};
// The caller.
int call(int i, int a, int b)
{
return functions[i](a, b);
}
The only problem that I can see in the solution from above is that there is no check for the array index (you may get some tricky problems).
To make the code more robust, you can add a check for the index (boundaries), like
add one if statement inside of function "call" where you check the parameter i (not to be bigger than the maximum value)

How can I solve this simple C function?

I am taking a hybrid class of "Algorithms, architecture, and assembly language" at my local community college. Although it's an intro class and mainly focuses on how computers turn code into binary, we have some assignments for C code. Some of the stuff we've never even gone over in class, and I'm lost.
The instructions read:
Write a function named DoSomething, with no return value, it should do just one (1) thing: multiply the global variable my_result by 5 and store the result back into my_result
You do not have to call DoSomething, or initialize my_result, I will do that.
I have tried
int my_result;
dosomething (my_result) {
my_result = my_result * 5;
}
but this is incorrect. I have almost zero experience with C language and am stuck. I'm not asking anyone to do my homework, I just want to understand. This has not been covered in class.
You almost have it. Since my_result is global, you do not need to pass it into the function, it is accessible everywhere. Oh, and every function needs its return value specified. Use void to specify that there is no return value and no parameters.
int my_result;
void dosomething (void) {
my_result = my_result * 5;
}
A correct function declaration must have a type, the name of the function and its arguments.
type function_name(type1 arg1, type2 arg2, type3 arg3, ...);
If a function does not return anything, then type must be void
void function_name(type1 arg1, type2 arg2, type3 arg3, ...);
If a function does not take any parameter, then the you can use void instead
of the list of arguements:
type function_name(void);
Your dosomething function is missing the return type, which should be void
(assignment says Write a function named DoSomething, with no return value)
and it takes no arguments (at least the assignment does not specify any), so the
correct prototype of the function must be:
void DoSomething(void);
So the correct program
#include <stdio.h>
int my_result;
void DoSomething(void)
{
my_result = my_result * 5;
}
int main(void)
{
my_result = 6; // initializing global variable
DoSomething();
printf("my_result: %d\n", my_result);
return 0;
}
which will print my_result: 30.
There is nothing to get worried about. Relax, it's just part of the process in becoming a good developer.
To solve such problems, first note what the function expects and we want from the function to return.
Now, in your question, it is given that function would return nothing. So the return type of the function would be void.
Now, since we have to use a global variable, it means function expects no argument.
Hence, our code is :
#include <stdio.h>
int my_result; // Our Global Variable
void doSomething (void) // Our Function
{
my_result = my_result * 5;
}
int main()
{
/* Asking the value of my_result */
printf("Please enter a value : ");
scanf("%d", my_result);
doSomething();
printf("\nNew value of my_result is : %d\n", my_result);
return 0;
}
// End of main.
The instructions read:
Write a function named DoSomething, with no return value,…
So code for that is:
void DoSomething(void)
… it should do just one (1) thing: Multiply the global variable my_result by 5 and store the result back into my_result.
And code for that is:
{
my_result = my_result * 5;
}
You do not have to call DoSomething, or initialize my_result, I will do that.
Done. The total code requested is:
void DoSomething(void)
{
my_result = my_result * 5;
}
You have indicated in your comments that you are submitting this code into some sort of automatic grading/checking software. So that software is designed to accept code that matches the assignment, no more and no less. Quite likely, it puts your code into a file and that compiles a source file that includes the former file with #include. That source file defines my_result and main, so your code should not, or it will cause compilation and/or link errors. You need to submit just the code requested in the instructions.
Notes about your code:
The instructions say to write a routine named DoSomething. You used dosomething. These are different in C; the case matters.
You declared the routine without specifying a return type. The instructions say the instruction has no return value, but that does not mean you should just omit any return type. You should explicitly say there is no return value by using void for the return type of the function, as in void DoSomething(…). (For historic reasons, if you omit the return type in a function declaration, it defaults to int. Letting the type default like that is old syntax and should be avoided.)
The instructions did not say whether the routine should take parameters. This is a shortcoming in the instructions. However, dosomething (my_result) is incorrect for two reasons. One, my_result is described as a global variable, not a parameter. Two, it is the wrong syntax for a parameter declaration. A parameter declaration must have a type, as in dosomething(int x). Since the routine needs no parameters, a proper declaration is void DoSomething(void). (Although there is some possibility the instructor intended void DoSomething(), but that would not generally be preferred.)

MATLAB C Coder return void

I've read some posts regarding my question. But I'm still not sure of the following:
I've generated Matlab's c coder to generate the c version of the findpeaks function. However, the functions generated all start with void or static void. Does that mean the functions won't return anything?
Thanks....
Functions generated by the C coder return void, so in fact nothing, but the values returned by the matlab function are 'returned' via pointers or arrays which come last in the arguments and which have their value set in the generated C code. This is done like this because matlab functions can return multiple values which you cannot do straightforward in C except by returning e.g. a struct or so.
Suppose your matlab function is
function [x,y] = Foo(a)
x = a + 1.0
y = 5 * ones(1,3)
then the generated C function declaration should be something like
void Foo(real_T a, real_T *x, real_T y[3]);
and if you call it like
real_T x;
real_T y[3];
Foo(0.0, &x, y);
then x will be set to 1.0 and y will be an array with all elements set to 5.
If a function looks like this:
void f(void);
then it can't return anything via its return value, so you can't say things like:
int n = f();
However, a function can also return values via its parameter list, using pointers:
void f( int * p ) {
* p = 42;
}
.....
int n;
f( & n ); // n now contains 42
or by setting global variables.
If the return type of a function is void, the function doesn't return any value.
According to Wikipedia's void type page:
The void type, in several programming languages derived from C and Algol68, is the type for the result of a function that returns normally but does not provide a result value to its caller. Usually, such functions are called for their side effects, such as performing some task or writing to their output parameters.

Function pointer with some parameters set

How can I create a function pointer to a function where some parameters are set to be fixed upon the definition.
Here is an example what I mean:
Let's say I have the function
int add (int n, int m) {
return n+m;
}
and the function pointer type
typedef int (*increaser)(int);
What I want is a pointer to the function add which fixes the first parameter to 1 and leaves the second paramenter open. Something along the lines of
increaser f = &add(1,x);
How can I accomplish this?
What I want is a pointer to the function add which fixes the first parameter to 1 and leaves the second paramenter open.
There is no such thing in C. The closest you can come is to create a wrapper function and make a pointer to that:
int add1(int x) {
return add(1, x);
}
increaser f = &add1;
If you don't need a pointer to the function then you can use a macro:
#define increaser(x) add(1, (x))
C does not support doing this directly. In C++ there is std::function and bind which can achieve this however.
None the less for a pure C solution the closest you can reasonably get is defining a new function that calls add like:
int increment(int input) {
return add(1, input);
}
Then you can do:
increaser f = &increment;

How to define an array of function pointers and the functions don't have same input argument definition?

Is it possible to define an array of function pointers (and the functions don't have se same input argument ) as indicating in the following code ?
If yes what I have to put in the function definition int (*handler)(/*what Ihave to put here ?*/);
struct handler_index {
const char *name;
int (*handler)(/*what Ihave to put here ?*/);
};
int handler0 (int a, int b)
{
printf("%d\n",a+b);
}
int handler1 (int a, int b, int c)
{
printf("%d\n",a+b+c);
}
int handler2 (int a, int b, int c, int d)
{
printf("%d\n",a+b+c+d);
}
const struct handler_index handler_index[] = {
[0] = {"handler0", handler0},
[1] = {"handler1", handler1},
[2] = {"handler2", handler3},
};
Just put nothing:
int (*handler)();
it means the function has an unspecified (but non-variable) number and types of parameters.
Any function that returns an int and with a fixed variable number of parameters can be assigned to handler.
Whilst int (*handler)() will indeed allow variable number of arguments for th function, I fail to see any benefit in this. Function pointers are useful when you have a piece of code that takes something, finds the "right thing to do" (e.g comparing the "name" with some input from elsewhere), and calls the function pointer to do whatever it has to do. The function pointer calling code needs to know how many arguments the function has (how else would it pass the right number and order of arguments.
I don't actually see any meaningful use of this at all. Yes, you can pass a variable number of arguments to a function, but the code HAS to know what arguments the function takes.
Unless the arguments are somehow specified in the definition of the struct - but then you need to define different content for the struct to allow for that.
I would suggest that you need to think about what you are trying to achieve, and then come up with a solution to the problem, most likely using a different method.
Put nothing. Just empty brackets.
int (*handler)();

Resources