r/C_Programming • • Mar 08 '24

Question ELI5: Void in C

I just began studying C and I cannot, for the life of me, understand void.

I have read and listened to many people say "It does not return a value". Ok? What is a value? Why wouldn't we want to return it? What is the difference between "void main" and "int main"? Can we just use int for everything and ignore void altogether?

In what situations is void used? In what situations is void better? etc. Please help I don't get it at all!

3 Upvotes

25 comments sorted by

87

u/saul_soprano Mar 08 '24

I think you’ll understand once you learn about functions

25

u/Marxomania32 Mar 08 '24 edited Mar 08 '24

"Returns" are what a function outputs. Specifically, it is what the function is evaluated to in a statement. For example, ignoring all side effects of func, the following line:

2 * func();

Is equivalent to:

2 * 10

If calling func returns 10.

C is a typed language, meaning that all values have an associated type that determines the semantics of that value. Function returns are values and also have types. A function can return a bool for example, and that return would then be interpreted as either being true or false. A function that returns void means it doesn't return anything. So if func above had type void, the entire statement would be invalid since you're multiplying 2 by nothing, which doesn't make any sense. A return type of void is used when you just want a function to execute a block of code, i.e. a procedure, and you don't need/care about what it "outputs."

1

u/DatBoi_BP Mar 08 '24

And even then, sometimes you will prefer to make such a function return an integer anyway, just to validate that things worked correctly (return 0) or not (return 1)

A practice I’ve become quite fond of is having different internal functions return either 0 or 2n (where n is unique for each function), and then have main() return the sum of these return values. This way, the combination of places where things went wrong is uniquely determined by the return value of main().

1

u/[deleted] Mar 09 '24

Although that's really interesting, there are only so many unique powers of two (and the bitsize of int is only guaranteed to be ≥16). And technically a non-zero value other than EXIT_FAILURE need not indicate failure, so e.g. return 1 may not actually indicate failure (and IIRC on VMS return 1 is actually not a failure condition). But these are just technicalities imo.

17

u/cHaR_shinigami Mar 08 '24

Before discussing void, it is worth noting that many things in C have different meanings depending on where and how they are used. For example, the asterisk acts as a binary operator in contexts like (a*b) (multiplication), and unary operator in (*a) (pointer dereferencing). Another example is the keyword static: it specifies internal linkage (aka private within a source file) when used externally (outside of a function), and specifies a non-automatic storage-class when used within a function. Likewise, the keyword void is used to mean several things depending on its usage:

  • As a return type, it says that the outcome of the function call expression is not a value that can be operated upon; this is often stated as the function doesn't return anything. While defining such functions, return statements cannot have values in them (only return; is permitted), and not writing a return statement at the end acts as if one had actually written return; at the end (just before the function closing brace).

  • For pointers, as in void *, it was standardized by the ANSI C committee that any object pointer (but not function pointer) can be implicitly cast to and from void * (before ANSI C/C89/C90, this was commonly done using char *, and perhaps for this historical reason C also requires that void * and char * have the same internal representation). C being a statically typed language (type checking done by the compiler on the source code before generating object code), one type of pointer cannot be assigned to another pointer to a non-compatible type, without telling the compiler that you are doing it consciously (by means of an explicit cast to the target pointer type). void * relaxes this requirement in C for object pointers. As a side note, POSIX further requires that even function pointers should be representable using void *.

  • void is also an incomplete type, i.e. a type for which sizeof (type) doesn't work. Furthermore, void type cannot be made complete by the programmer (as can be done with incomplete structs for example). It is often used to indicate to the compiler that something is unused; for example, a compiler may warn that the expression a = a is redundant, but most compilers ignore this if an explicit cast to void is applied, like so: (void)(a = a). A common practice is to do this for function parameters that are otherwise unused (such as the statement (void)unused_param;)

2

u/DatBoi_BP Mar 08 '24

As an aside to your first bullet: in the case of int func()…, do some compilers automatically include return 0 if the user doesn’t provide a return value? I want to say I’ve heard it happens in some cases but idk if that’s true, or even if I’m thinking of C in the first place.

2

u/cHaR_shinigami Mar 09 '24

That's a special rule only for int main (since C99), but not for other functions returning int.

2

u/DatBoi_BP Mar 09 '24

Gotcha! Thank you

11

u/glasket_ Mar 08 '24

What is a value?

Data. Something encoded by bytes, with an associated type to tell you how to read it.

Why wouldn't we want to return it?

You might not have anything meaningful to return, or it might be redundant.

What is the difference between "void main" and "int main"?

Well in this case a lot, main is special and isn't allowed to return void, but in the case of other functions void F means F doesn't return a value while int F means F returns an integer value.

Can we just use int for everything and ignore void altogether?

You could, but it's hard to ignore void entirely since you will use void functions at some point.

In what situations is void used? In what situations is void better?

When you want to indicate that a function is only executed for its side effects. You could have an entire philosophical debate over if that should ever be considered "better," but that's essentially the key meaning of void: it doesn't return anything and so its impact on the program comes from mutating state.

1

u/DatBoi_BP Mar 08 '24

Can main() return a non-int value? I realize now I’ve never tried.

2

u/glasket_ Mar 08 '24

It's UB to use anything other than int, unless your implementation specifies otherwise.

The function called at program startup is named main. The implementation declares no prototype for this function. It shall be defined with a return type of int and with no parameters or with two parameters (referred to here as argc and argv, though any names may be used, as they are local to the function in which they are declared) or equivalent; or in some other implementation-defined manner.
C23 5.1.2.3.2 ¶ 1

1

u/[deleted] Mar 09 '24

In my mind, void functions also means "Yay, this function doesn't return any error code, so I don't need to check for errors."

2

u/[deleted] Mar 08 '24

For function return values, you could always return int, for example 0, and just never use it. But if it means nothing, then it adds meaningless stuff to the code, making it longer and less clear. Also, if you return int, you may accidentally use the function in an expression. With void, you get compiler error.

Some languages have separate functions which return a value, and procedures/subroutines which do not. In C the same is done by setting return value type to void.

You can't have void variable, compiler needs to know the type to know the size etc. But void*, void pointer, is important. It is a pointer variable, but it does not tell what it points to, the code must somehow know. Example is malloc returning void*, and then it is up to the programmer what to do with the memory.

2

u/zhivago Mar 08 '24

If a value is returned it should be meaningful, and so should be used -- ignoring a return value is a red flag.

If there is no meaningful return value, it's better not to return it, so that people don't try to use it.

1

u/57thStIncident Mar 08 '24

One distinction that you might not have picked up on yet is "void" vs "void*". The former is essentially absence of a value -- a function declared to return void won't return anything and the compiler will complain if you try to return something or try to capture a return value from such a function. "void*" on the other hand is data, holding the memory address to something of unknown type. "void" is sort of a syntactic place holder. In addition to "void doSomething();" you can also have "int getSomething(void);". The latter is perhaps more often simply written as "int getSomething();", my suspicion is that the former may have been required on some very old compilers for functions that take no arguments.

1

u/TheChief275 Mar 11 '24

I heard that without funcName(void) users could pass any number of arguments they want and that might fuck something up. Not sure though, I primarily specify void as parameter to be explicit.

1

u/venkat_1924 Mar 08 '24

All return types such as void, int, etc only come up when we talk about functions. Now think of a function as a black box. You feed it some values, and it does something with those values.

Now maybe you want the function to return the output (you feed it two numbers to add, it returns the sum, here the function returns an int or float or etc).

Maybe the task the function is performing doesn't need it return an output, just to do its task. For example, a function to sort an array of integers would have you pass in a pointer to an array of numbers to sort, and it sorts the array. But what would you return here? You just want the function to sort the array and then you want to move on to the next thing. You don't need any feedback from the sorting function here. So here, you'd define the function with a void return type, because you don't need it to return any value. Just perform the task and leave it at that.

Tl;dr:
Why use a void return type for a function?

  • Just get it done: Sometimes, you just want something done, like sorting your socks (sort function). You don't need the box (function) to hand you back the sorted socks, you just want them sorted!

  • Not applicable: Maybe the function doesn't have anything useful to return. Like a function to print a message to the screen (print function). It does its job (shows the message), but there's no value to return because it's just displaying information.

1

u/[deleted] Mar 08 '24

Void is just anything/nothing.

A function of type void is a function that does not return any value, so you can use it where you don't need a return value.

The keyword void is also used for data when it is near the pointer symbol '*'. That specifies a type that is a pointer variable and that it can point to any type of data, thus it's castable to any other type of data implicitly (only in C, not in C++).

Let's give an example.

void setData(void* data);

Is a function that returns no data, so you cannot do:

int x = setData(data);

And it takes a pointer to any sort of data, because the type is not specified (void).

int data = 1234;

setData(&data); //we are passing a int* to the function. The cast is implicit.

Another example is this:

void increment(int* i) { (*i)++; }

int a = 3;

increment(&a);

// now the variable contains the value 4

In the last example we used an int* in the place of void* because dereferencing an int* gives an int, so we could use it to increment, while dereferencing a void* will result in a compile-time error

1

u/[deleted] Mar 08 '24 edited Mar 08 '24

A value is a piece of data, usually a number of some kind.

Functions are subprograms that maybe take in parameters and maybe give a value back. They can also do things, like create files or display stuff to the screen.

If a function takes no parameters, you give it an argument of void.

If it returns (gives back) no value, it returns void.

The "main" function takes two parameters given by the OS: the number of command line flags, and an array of the text of those flags.

It also returns a value to the OS when the program ends: an integer (int) that the OS can use as an error code.

That is why main has "int" return type.

Most compilers will let you also make the "main" function "void", in which case the program still returns an exit code (in this special case), but the value is not defined by the C language standard. Most compilers for desktop architectures will return 0.

For any other function, a void function has no return value ever. You will get an error if you try to store a returned value in a variable.

1

u/arkt8 Mar 08 '24

Think of `void` as a type. It is intended to manifest the intention of "unspecified".

The most common uses are in functions or structs.

void myfunc(int x);

When preceding the name of a function in a declaration or definition, it express the function should return nothing.

void *myfunc(int x);

When preceding a star before a function name, it express that the function return is a pointer of unspecified type. This is the case, for example, of the `malloc()`function. You asked the difference of `int main` and `void main`, so basically `int main()` _should_ return an int while `void main()` should return nothing. Note that `main()` function should always return exit status of the program (0 for success). So `void main`is a bad practice...

int main(void);

When used as the only argument in a function, express that the function doesn't receives an argument. It is a recommended practice.

Structs

It is used in a struct in the form `void *` to express that the struct member is a pointer that can point to any type of data (as void means unspecified type).

1

u/TheFlamingLemon Mar 09 '24

You can return int and just ignore it, but it’s bad practice for a number of reasons

0

u/[deleted] Mar 08 '24

in C, we can have a function that takes a value and returns a value like, int func(int a){return a+1;}.

we can also have a function that does not return any value, void func(int a){return;}. Notice the syntax return;.

This kind of function is usefull, like for setting up global variables like, int global=0;void func(int a){global=a;}, or doing pointers magic, void func(int a, char **s){static char *even="even"; static char *odd = "odd"; *s = (a & 1 ? odd : even);}

Hopes that usefull.

0

u/brendel000 Mar 08 '24

Just read the first chapters of your class/book, what is the point to explain the very basic of programming here

0

u/[deleted] Mar 08 '24

[deleted]

1

u/modlover04031983 Mar 08 '24

I actually started with python, Decided to switch to javascript, Then to Webgl, Then to ShaderToy, Then to C++.

0

u/[deleted] Mar 08 '24

[deleted]

1

u/futuranth Mar 08 '24

But if you need to return something else, you can use any data type for the function. fopen() for example returns a FILE pointer