|
|
|||||||||
|
|||||||||
| |||||||||
|
|
|
| |||||||||
![]() |
|
|
«
Previous Thread
|
Next Thread
»
|
Thread Tools | Search this Thread | Rate Thread | Display Modes |
|
#1
|
|||
|
|||
|
what do the different voids do?
Can anyone explain to me the purpose of using void and the different ways to use it when using functions?
|
|
#2
|
||||
|
||||
|
Basically, the void keyword is used to specify that a function takes (or returns) no parameters, depending on where you put it. For example:
int function1(void); void function2(int, char); void function3(void); In the above example, function1 takes no arguments and returns an int, function2 takes 2 arguments, but returns nothing and function3 takes no arguments and returns no arguments. The one special case is the void pointer (void *), which does actually return (or take) a generic pointer, but you have to type cast the pointer to another type, before using it. A commonly used function of this type is the malloc() function which is prototyped something like this: void *malloc(int n_bytes) and the usage goes something like this: Code:
int *i; char *c; i = (int *)malloc(50 * sizeof(int)); /* Allocate 50 integer array */ c = (char *)malloc(20 * sizeof(char)); /* Allocate 20 char array */ |
|
#3
|
|||
|
|||
|
Another usage is void *.
This really is completely different than a void. if x is declared as: void *x; then x is a pointer to "nothing" (some unknown thing). if something is a pointer to nothing, that means it could be a pointer to anything. Its up to you to know the right thing to cast it to. Don't do this until you understand exactly why you would need to. Even then think about it for ten minutes and try to talk yourself out of it. |
![]() |
| Viewing: Dev Shed Forums > Programming Languages > C Programming > what do the different voids do? |
| Thread Tools | Search this Thread |
| Display Modes | Rate This Thread |
|
|
|
|