Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Generic keyword in C ?
As we know that the Macros are used in C or C++, but there is no facility for type checking. The macros can take any type of argument in it. The following example will show this case clearly.
Example
#include<stdio.h>
#define INCREMENT(X) ++X
main() {
int x = 5; float y = 2.56; char z = 'A';
printf("Integer Increment: %d
", INCREMENT(x));
printf("Float Increment: %f
", INCREMENT(y));
printf("Character Increment: %c
", INCREMENT(z));
}
Output
Integer Increment: 6 Float Increment: 3.560000 Character Increment: B
That is the problem of macro. In the later version of C, we can use macro by using ‘_Generic’ keyword. Using this we can define macro using different types of datatypes. Let us see one example.
Example
#include<stdio.h>
#define INCREMENT(X) _Generic( (X), char: X+10, int: X+1, float: X+2.5, default: 0)
main() {
int x = 5; float y = 2.56; char z = 'A';
printf("Integer Increment: %d
", INCREMENT(x));
printf("Float Increment: %f
", INCREMENT(y));
printf("Character Increment: %c
", INCREMENT(z));
}
Output
Integer Increment: 6 Float Increment: 5.060000 Character Increment: K
Advertisements