By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
431,650 Members | 812 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 431,650 IT Pros & Developers. It's quick & easy.

what is the purpose of using void keyword

P: 1
What is the main purpose of using void keyword
Sep 25 '16 #1
Share this Question
Share on Google+
2 Replies

Expert Mod 5K+
P: 9,197
In C you cannot have multiple functions with the same name. Like this:

Expand|Select|Wrap|Line Numbers
  1. int Area(Circle* x);
  2. int Area(Square* x);
  3. int Area(Triangle* x);
The workaround is to use a void pointer. The keyword void just means "no-type". The you supply a second argument to explain the void pointer:

Expand|Select|Wrap|Line Numbers
  1. int Area(void* x, int y);
May y=1 means the x argument is a Circle whereas y = 2 may mean the x argument is a Square.

This allows the function to typpecast the void* to the correct type and do the calculation.

This situation does not arise in C++ where function names are identitifed by their signature and not by their names.

The other place you see void is as a function return type:

Expand|Select|Wrap|Line Numbers
  1. void func(int arg);
This tells the compiler that no type is returned making this an error:

Expand|Select|Wrap|Line Numbers
  1. int val = func(10);
Without the void return, the function is assumed to return an int. Now the code passes the compile OK but crashes at run time when val is garbage.
Sep 25 '16 #2

Expert 100+
P: 2,398
A void* pointer can be assigned a value that points to any data type. You should not assign a function pointer value to it.

This function prototype declares a function that takes no arguments. You will get a compiler error if you pass any arguments to it.
int func(void);

Notice that this declaration is different than the previous case.
int func();
In this case, there is no function prototype. The compiler will allow any number of arguments of any type.

You can cast a statement to void to instruct the compiler that you are intentionally discarding the value of the statement. You get the same effect whether you cast to void or not. I suppose the point of being explicitly intentional is to make your intentions clear to the next person to read your code; doing so may also prevent some compiler warnings. Some examples of this usage:
(void) printf("%d\n", var);

That last one is an idiom that shows up from time to time when you want a statement that does nothing. You almost always want your statements to do something, so this idiom is only seen in very uncommon special situations.
Sep 28 '16 #3

Post your reply

Sign in to post your reply or Sign up for a free account.