Void

The Void data type indicates absence of any data type.

 

3 primary uses:

  • Void function returns
  • Void function arguments
  • Void pointers

 

Void function returns

Used when no return value is required or expected:

void myFunc() {
	printf("All this does is print this!\n") ;
}

As can be seen in this very simple function, which simply prints a line of text, no return value is given or expected.

 

 

Void function arguments

Used where a function does not expect or accept an argument/parameter:

int rand(void) ;

 

 

Void pointers

Can be used to point to ANY data type of object.

 

Represents the address of an object but not its data type.

 

Can be assigned to ANY data type of object.

 

CANNOT be dereferenced directly - HAS to be typecast to the data type of the object being pointed to.

 

#include <stdio.h>
#include <stdlib.h>

int main () {

	int myInt = 12 ;
	int *pMyInt;
	float myFlt = 14.634572;
	float *pMyFlt;

	void *vPtr ;              //declare a void pointer

	vPtr = &myInt ;           //assign address of myInt to void pointer

	//assign void pointer to int pointer
	pMyInt = vPtr ;               //implicit cast (only in C, not c++)
	printf("value: %d \n", *pMyInt ) ;

	vPtr = &myFlt ;                  //assign address of myFlt to void pointer

	//assign void pointer to float pointer
	pMyFlt = vPtr ;               //implicit cast (only in C, not c++)
	printf("value: %f", *pMyFlt); //

return 0;
}

Compile & Run:

value: 12
value: 14.634572

 

 

source

Leave a Reply