0% found this document useful (0 votes)
71 views

C Concepts

The document discusses C preprocessor macros and directives. It defines macros as code segments that get replaced by their defined values. There are two types of macros - object-like and function-like. It also explains common predefined macros like _DATE_ and _FILE_, and preprocessor directives like #include, #define, #ifdef, #ifndef, #if, #else, #undef that control code flow. Sample code is provided to demonstrate the use of these macros and directives.

Uploaded by

Avirup Ray
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
71 views

C Concepts

The document discusses C preprocessor macros and directives. It defines macros as code segments that get replaced by their defined values. There are two types of macros - object-like and function-like. It also explains common predefined macros like _DATE_ and _FILE_, and preprocessor directives like #include, #define, #ifdef, #ifndef, #if, #else, #undef that control code flow. Sample code is provided to demonstrate the use of these macros and directives.

Uploaded by

Avirup Ray
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 12

C

No. Macro Description


Macros
1 _DATE_ represents current date in "MMM DD YYYY" format. A macro is a
segment of code
2 _TIME_ represents current time in "HH:MM:SS" format.
which is replaced
3 _FILE_ represents current file name.
by the value of
macro.
4 _LINE_ represents current line number. Macro is defined
by #define
5 _STDC_ It is defined as 1 when compiler complies with the ANSI standard.
directive.
There are two
types of macros:
1. Object-like Macros
2. Function-like Macros

Object-like Macros

The object-like macro is an identifier that is replaced by value.


It is widely used to represent numeric constants.
For example: #define PI 3.14  

Here, PI is the macro name which will be replaced by the value 3.14.

Function-like Macros
The function-like macro looks like function call. For example:
1. #define MIN(a,b) ((a)<(b)?(a):(b))    

Here, MIN is the macro name.


Visit #define to see the full example of object-like and function-like macros.

C Predefined Macros
ANSI C defines many predefined macros that can be used in c program.

File name: simple.c


#include<stdio.h>
int main()
{
printf("File :%s\n", __FILE__ );
printf("Date :%s\n", __DATE__ );
printf("Time :%s\n", __TIME__ );
printf("Line :%d\n", __LINE__ );
printf("STDC :%d\n", __STDC__ );
return 0;
}

Output:
File :simple.c
Date :Dec 6 2015
Time :12:28:46
Line :6
STDC :1

C Preprocessor Directives
The C preprocessor is a micro processor that is used by compiler to transform your code before
compilation.
It is called micro preprocessor because it allows us to add macros.

Note: Proprocessor direcives are executed before compilation.


Note:-All preprocessor directives starts with hash # symbol.

Let's see a list of preprocessor directives.


o #include
o #define

o #undef
o #ifdef
o #ifndef
o #if

o #else
o #elif
o #endif

o #error
o #pragma

C #include
1.> The #include preprocessor directive is used to paste code of given file (filename) into current file
(where we are writing program) .
2.> It is used include system-defined and user-defined header files.
3.> If included file is not found, compiler renders error.

By the use of #include directive, we provide information to the preprocessor where to look for the
header files. There are two variants to use #include directive.
1. #include <filename>
2. #include "filename"

The #include <filename> tells the compiler to look for the directory where system header files are held.
The #include "filename" tells the compiler to look in the current directory from where program is
running.

#include directive example


Let's see a simple example of #include directive. In this program, we are including stdio.h file because
printf() function is defined in this file.
1. #include<stdio.h>  
2.  int main()
3. {    
4.    printf("Hello C");      
5.    return 0;  
6.  }   

#include notes:
Note 1: In #include directive, comments are not recognized. So in case of #include <a//b>, a//b is
treated as filename.
Note 2: In #include directive, backslash is considered as normal text not escape sequence. So in case of
#include <a\nb>, a\nb is treated as filename.
Note 3: You can use only comment after filename otherwise it will give error.

C #ifdef
1.) The #ifdef preprocessor directive checks if macro is defined by #define.
2.) If yes, it executes the code
3.) otherwise #else code is executed, if present.
#include <stdio.h> #include <stdio.h> Syntax:
void main() #ifdef MACRO  
#define NOINPUT { //code  
void main() int a=0; #endif  
{ #ifdef NOINPUT
int a=0; a=2; Syntax with #else:
#ifdef NOINPUT #else #ifdef  MACRO  
a=2; printf("Enter a:"); //successful code  
#else scanf("%d", &a); #else  
printf("Enter a:"); #endif //unsuccessfull  code  
scanf("%d", &a); printf("Value of a: %d\n", a); #endif  
#endif }
printf("Value of a:
%d\n", a);
}
Output: 1.) if macro NOINPUT is not
Value of a: 2 defined…you will be prompted
to enter value of a
2) Output:
Enter a: 5
Value of a: 5

C #ifndef
1.> The #ifndef preprocessor directive checks if macro is not defined by #define.
2.> If yes, it executes the code
3.> otherwise #else code is executed, if present.

#include <stdio.h> #include <stdio.h> Syntax:


#ifndef MACRO  
void main() #define NOINPUT //code  
{ void main() #endif  
int a=0; {
#ifndef NOINPUT int a=0; Syntax with #else:
a=2; #ifndef NOINPUT #ifndef  MACRO  
#else a=2; //successful co
printf("Enter a:"); #else #else  
scanf("%d", &a); printf("Enter a:"); //unsuccessfull
#endif scanf("%d", &a); #endif  
printf("Value of a: %d\n", a); #endif
} printf("Value of a: %d\n", a);
}
Output: 1.) if macro NOINPUT is defined…you will
Value of a: 2 be prompted to enter value of a
2) Output:
Enter a: 5
Value of a: 5
C #if
1.>The #if preprocessor directive evaluates the expression or condition.
2.>If condition is true, it executes the code
3.>otherwise #elif or #else or #endif code is executed.

Syntax:
1. #if expression  
2. //code  
3. #endif  

Syntax with #else:


1. #if expression  
2. //if code  
3. #else  
4. //else code  
5. #endif  

Syntax with #elif and #else:


1. #if expression  
2. //if code  
3. #elif expression  
4. //elif code  
5. #else  
6. //else code  
7. #endif  

C #if example
Let's see a simple example to use #if preprocessor directive.
1. #include <stdio.h>  
2. #include <conio.h>  
3. #define NUMBER 0  
4. void main()
5.  {  
6. #if (NUMBER==0)  
7. printf("Value of Number is: %d",NUMBER);  
8. #endif         
9. getch();  
10. }  

Output:
Value of Number is: 0

Let's see another example to understand the #if directive clearly.


1. #include <stdio.h>    
2. #include <conio.h>    
3. #define NUMBER 1  
4. void main()
5.  {  
6.   
7. #if (NUMBER==0)  
8. printf("1 Value of Number is: %d",NUMBER);  
9. #endif  
10.   
11. #if (NUMBER==1)  
12. printf("2 Value of Number is: %d",NUMBER);  
13. #endif  
14. getch();  
15. }  

C #undef
The #undef preprocessor directive is used to undefine the constant or macro defined by #define.

Syntax:
1. #undef MACRO_NAME 

Let's see a simple example to define and undefine a constant.


1. #include <stdio.h>  
2. #define PI 3.14  
3. #undef PI  
4. main()
5.  {  
6.     printf("%f",PI);  
7. }  
Output:
Compile Time Error: 'PI' undeclared

The #undef directive is used to define the preprocessor constant to a limited scope so that you can
declare constant again.

Let's see an example where we are defining and undefining number variable. But before being
undefined, it was used by square variable.
1. #include <stdio.h>  
2. #define number 15  
3. int square=number*number;  
4. #undef number  
5. Int main() 
6. {  
7.     printf("%d",square); 
8. Printf("%d",number);//Compile Time Error : Pi undeclared 
9. }  

Output:
225

Interesting Facts about Macros


and Preprocessors in C
In a C program, all lines that start with # are processed by preprocessor which is a special program
invoked by the compiler. 
In a very basic term, preprocessor takes a C program and produces another C program without any #.

Following are some interesting facts about preprocessors in C.

1) When we use include  directive,  the contents of included header file (after preprocessing) are copied
to the current file.
Angular brackets  < and > instruct the preprocessor to look in the standard folder where all header
files are held. 
Double quotes  “ and “ instruct the preprocessor to look into the current folder (current directory).

3) The macros can take function like arguments, the arguments are not checked for data type.
For example, the following macro INCREMENT(x) can be used for x of any data type.

#include <stdio.h>
#define INCREMENT(x) ++x
int main()
{
char *ptr = "GeeksQuiz";
int x = 10;
float y=10.0f;
double z=10.0;
printf("%s\n ",INCREMENT(ptr));
printf("%d\n",INCREMENT(x));
printf("%f\n",INCREMENT(y));
printf("%f\n",INCREMENT(z));

return 0;
}

Output:
eeksQuiz
11
11.000000
11.000000

4) The macro arguments are not evaluated before macro expansion.

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


#define MULTIPLY(a, b) a*b //here, instead of writi
int main() #define MULTIPLY(a, b
{ int main()
     {
    printf("%d", MULTIPLY(2+3, 3+5)); // The macro is expended as 2 + 3 * 3 + 5, not as 5*8     printf("%d", MULTIP
    return 0; expended as (2 + 3) *
}     return 0;
}

Output: Output:
16 40

5) The tokens passed to macros can be concatenated using operator ## called Token-Pasting


operator.

#include <stdio.h>
#define merge(a, b) a##b
int main()
{
    printf("%d ", merge(12, 34));
}

Output:
1234

6) A token passed to macro can be converted to a string literal by using # before it.

#include <stdio.h>
#define get(a) #a
int main()
{
printf("%s\n", get(GeeksQuiz));//GeeksQuiz is converted to string i.e "geeksQuiz"
printf("%u\n", get(123));//123 is converted to string "123" and base address of this string is printed
printf("%u\n", get(Ali is Great)); //Ali is Great is converted to string "Ali is Great" and base address of this string is pr
printf("%s\n", get(Muhamad bin Qasim)); // Muhamad bin Qasim is converted to string i.e " Muhamad bin Qasim "
}

Output:
GeeksQuiz
4206638
4206646
Muhammad Bin Qasim

7) The macros can be written in multiple lines using ‘\’. The last line doesn’t need to have ‘\’.

#include <stdio.h>
#define PRINT(i, limit) while (i < limit) \
                        { \
                            printf("GeeksQuiz\n "); \
                            i++; \
                        }
int main()
{
     int i = 0;
     PRINT(i, 3);
     return 0;
}

Output:
GeeksQuiz
GeeksQuiz
GeeksQuiz

12) We can remove already defined macros using : #undef MACRO_NAME

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


#define LIMIT 100 #define LIMIT 1000
int main() int main()
{ {
   printf("%d",LIMIT); //removing    printf("%d",LIMIT);//1000
defined macro LIMIT //removing defined macro LIMIT
   #undef LIMIT    #undef LIMIT
   //Next line causes error as LIMIT is not    //Declare LIMIT as integer again
defined    int LIMIT=1001;
   printf("%d",LIMIT);    printf("\n%d",LIMIT); //1001
   return 0;    return 0;
} }

Q1. Predict the output


#include <stdio.h> #include <stdio.h>
#if X == 3 #define X 3
    #define Y 3 #if !X
#else     printf("Geeks");
    #define Y 5 #else
#endif     printf("Quiz");
      
int main() #endif
{
    printf("%d", Y); int main()
} {
        return 0;
}

Output:- 5 Output:- Compiler Error


1) In the first look, the output seems to be compile- 1) A program is converted to executable using follow
time error because macro X has not been defined a) Preprocessing
2) In C, if a macro is not defined, the pre-processor b) C code to object code conversion
assigns 0 to it by default. c) Linking
3) Hence, the control goes to the conditional else part
and 5 is printed. 2) After Step 1 we have
printf("Quiz");
int main()
{
return 0;
}

3) This is wrong bcoz the printf is called outside

Q2. Predict the output


#include <stdio.h>  Which file is generated after pre-processing of a C
#define f(g,g2) g##g2  program?
int main()  (A) .p
{  (B) .i
    int var12 = 100;  (C) .o
    printf("%d", f(var,12));  // 100 (D) .m
    return 0; 
}

Output:- 100
1) The operator ## is called “Token-Pasting” or 1) After the pre-processing of a C program, a .i file is
“Merge” Operator generated which is passed to the compiler for
2) It merges two tokens into one compilation.
2) It concatenates all the parameters into one
token.
3) printf("%d ",f(var,12));  printf("%d ",var12);
Q3. Predict the output
#include <stdio.h> #include <stdio.h>
#define macro(n, a, i, m) m##a##i##n #define get(s) #s
#define MAIN macro(n, a, i, m)   
   int main()
int MAIN() {
{     char str[] = get(GeeksQuiz);
    printf("GeeksQuiz");     printf("%s", str); //GeeksQuiz
    return 0;     return 0;
} }

Output:- GeeksQuiz Output:- GeeksQuiz


1) The operator ## is called “Token-Pasting” or 1) A token passed to macro can be converted to a string
“Merge” Operator literal by using # before it.
2) It merges two tokens into one 2
2)  It concatenates all the parameters into one token.
3) MAIN is replaced by macro (n,a,i,m)  main

Q4. Concept of Memory Leak


1) Memory leak occurs when programmers create a memory in heap and forget
to delete it.
2) To avoid memory leaks, memory allocated on heap should always be freed
when no longer needed.
3) Memory leaks are particularly serious issues for programs like daemons and
servers which by definition never terminate.

Memory Leak occurs No Memory Leak occurs


#include <stdlib.h> #include <stdlib.h>
void f() void f()
{ {
    int *ptr = (int *)     int *ptr = (int *) malloc(sizeof(int));
malloc(sizeof(int));    /* Do some work */
   /* Do some work */ free(ptr);
return; /* Return without freeing return;
ptr*/ }
}

You might also like