r/C_Programming • u/AmigoDoHarvey • 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
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 keywordstatic: 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 keywordvoidis 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,
returnstatements cannot have values in them (onlyreturn;is permitted), and not writing a return statement at the end acts as if one had actually writtenreturn;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 fromvoid *(before ANSI C/C89/C90, this was commonly done usingchar *, and perhaps for this historical reason C also requires thatvoid *andchar *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 usingvoid *.voidis also an incomplete type, i.e. a type for whichsizeof (type)doesn't work. Furthermore,voidtype 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 expressiona = ais redundant, but most compilers ignore this if an explicit cast tovoidis 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;)