mb2g17
mb2g17

Reputation: 145

What can a void variable be used for?

For example, if I made the variable:

void helloWorld;

What could I do with it? Since it represents nothing, at first I thought that nothing could be done with it. I am aware that functions use void for no return value, but do the variables have a purpose?

-- EDIT --

I have found out the answer. I am now aware that void variables are illegal in programming languages such as Java, C++ and C. Thanks for all of your answers!

Upvotes: 10

Views: 8016

Answers (5)

James Morris
James Morris

Reputation: 4935

In C you can cast function parameters to void

(void)myarg;

this is only useful for dealing with unused parameter warnings however.

Upvotes: 1

haccks
haccks

Reputation: 106012

C99 6.2.6 paragraph 19 says:

The void type comprises an empty set of values; it is an incomplete type that cannot be completed.

Also, void in C, is a type that has no size. Thus, if you were to declare a variable of type void, the compiler would not know how much memory to allocate for it.
So, you can't declare a void variable because it is of incomplete type.

void is useful just when we're talking about pointers (void*) since it allows you to declare a generic pointer without specifying the type.

Read this answer given by Keith Thompson for more detailed explanation.

Upvotes: 6

nikhil
nikhil

Reputation: 201

i think you don't know what 'void' is??? do you..

small and quick info about void

void is not a data-type like int or char that you use to declare variables.

void is a return-type

void return type is used to say that we are returning nothing from this function.

if you don't return anything then you have to write void as return-type for a function (including main function). alternatively you can say ....

return 0;

at the end of function's definition.

i hope this might helped you to understand what is void.

Upvotes: 0

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 279910

In Java, you cannot use void as a variable type.

You can however use Void

The Void class is an uninstantiable placeholder class to hold a reference to the Class object representing the Java keyword void.

You won't be able to do anything with it, except get the Class object, but that is a static field anyway so you don't need an object reference.

Upvotes: 3

Sergey L.
Sergey L.

Reputation: 22542

void variables are invalid in C/C++ because the compiler can not determine their size. void is only valid as function argument list (takes no arguments) or return types (returns nothing).

There is void * which just means "any type pointer" and is a generic pointer type, but you are not allowed to dereference it.

Upvotes: 11

Related Questions