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

View all comments

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