Common C Programming Mistakes : Preprocessor Errors

Preprocessor processes given source code before giving it to the compiler.Preprocessor must be used with care. Some of the Common mistakes while using preprocessor are as below –

Mistakes while writing C Preprocessor directives :

Macro expansion should be enclosed within parenthesis

#include<stdio.h>
#include<conio.h>
#define SQU(x) x*x

void main()
{
int num ;
clrscr();
num = SQU(2)/SQU(2);
printf("Answer : %d",num);
getch();
}

Output :

Answer : 4

Explanation of Program :
Above expression will be expanded as –

SQU(x) / SQU(x) = [ x*x / x*x]
                = [ x*x/x*x  ]
                = [   x*x    ]
                = [   x^2    ]

In the program the macro #define substitutes SQU(2) by just 2*2 not by 4. thus –

SQU(2) / SQU(2) = [ 2*2 / 2*2]
                = [ 2*2/2*2  ]
                = [   2*2    ]
                = [   2^2    ]
                = [    4     ]

In order to avoid the above problem we can write like –

#define SQU(x)((x)*(x))

Do not Leave blank between macro-template and its argument

#define SQU(x)((x)*(x))//Write like this
  • Do not give space between SQU and (x)  , as it becomes the part of macro expansion
  • It results into Improper result OR Compile time Error

Do not Give semicolon at the end of #define statement .

#define SQU(x)((x)*(x));//Do not give semicolon at the end

Allot one line for each macro preprocessor

#include<stdio.h>
#include<conio.h>// Write on separate line

Do not write like this

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

#pragma warn Macro Directive in C | Suppress Warning Messages

Topics : How to Suppress Warning Messages in C ?

  1. What is Warning Message in C ?
  2. What is Error and Message in C ?
  3. #pragma warn Directive in C
  4. Live Example
  5. List of Warning Codes in ANSI

Warning Message :

  • A warning is a non-critical condition that does not require immediate attention.
  • Warning can be ignored.
  • Waring will never stop your execution of C Program.

Error Message

  • An Error is a critical condition that requires immediate attention.
  • Error messages cannot be ignored.
  • Compile Error won’t let you to run C Program.
  • run Time Error will terminate current execution of C program

#pragma warn Macro Directive in C

  1. In c there are many warning messages which can be on or off with help of #pragma warn.

Syntax :

#pragma warn +xxx
#pragma warn –xxx
#pragma warn .xxx

Where

+ means on
- means off
. means on/off (toggle)
  1. xxx is indicate particular warning code in thee alphabet.
  2. Example :  rvl  warning code means function should return a value.

Live Example :

#include<stdio.h>

#pragma warn –rvl

int main(){

printf("It will not show any warning message");

}

Explanation :

  1. -rvl mean suppress warning message .
  2. rvl means : “Function should return a value“.
  3. We have specified return type of main as “Integer” but we are not going to return a value.
  4. Usually this program will show warning message.
  5. We have suppressed warning already (-rvl) so we won’t get any warning message.
  6. Standard notation and there actual meaning is shown inside following table –

List of Warning Codes in C

S.N.
Warning message
Code
ANSI Violations
1
Assigning ‘type’ to ‘enumeration’
eas
2
Bit fields must be signed or unsigned int
bbf
3
Both return and return with a value used
ret
4
Declare type ‘type’ prior to use in prototype
dpu
5
Division by zero
zdi
6
Hexadecimal value contains more than 3 digits
big
7
Initializing ‘enumeration’ with ‘type’
bei
8
‘identifier’ is declared as both external and static
ext
9
Ill-formed pragma
ill
10
Initialization is only partially bracketed
pin
11
Redefinition of ‘macro’ is not identical
dup
12
Suspicious pointer conversion
sus
13
Undefined structure ‘structure’
stu
14
Void functions may not return a value
voi
Frequent Errors
1
Code has no effect
eff
2
Function should return a value
rvl
3
Parameter ‘parameter’ is never used
par
4
Possible use of ‘identifier’ before definition
def
5
Possibly incorrect assignment
pia
6
Unreachable code
rch
Less Frequent Errors
1
Ambiguous operators need parentheses
amb
2
Array variable ‘identifier’ is near
ias
3
Call to function with no prototype
pro
4
Call to function ‘function’ with no prototype
pro
5
Condition is always false
wccc
6
Condition is always true
wccc
7
‘identifier’ declared but never used
use
8
‘identifier’ is assigned a value that is never used
aus
9
No declaration for function ‘function’
nod
10
Structure passed by value
stv
11
Superfluous & with function
amp
Portability Warnings
1
Constant is long
cln
2
Constant out of range in comparison
rng
3
Conversion may lose significant digits
sig
4
Non portable pointer comparison
cpt
5
Non portable pointer conversion
rpt
6
Mixing pointers to signed and unsigned char
ucp

Pre-processor to Define String in C Programming

Pre-processor to Define String in C Programming

Program to define Printf Statement using #define

#include<stdio.h>
#define PRINT printf("%s",str)

void main()
{
char *str = "Pritesh";
PRINT;
}

Output :

Pritesh

Program to define String

#include<stdio.h>
#define STR "Pritesh Taral"

void main()
{
printf("%s",STR);
}

Output:

Pritesh Taral

Program to use format specifier inside MACRO

#include<stdio.h>
#include<conio.h>
#define FORMAT "%s",str

void main()
{
clrscr();
char *str="Pritesh";
printf(FORMAT);
}

Output :

Pritesh

#pragma startup and #pragma exit directive in c Programming Language

#pragma startup and #pragma exit directive in c Programming Language

Syntax : startup pragma

#pragma startup <function_name> [priority]
  • startup pragma allow the program to specify function(s) that should be called upon program startup
  • Function is called before main().

Syntax : exit pragma

#pragma exit <function_name> [priority]
  • exit pragma allow the program to specify function(s) that should be called just before the program terminates through _exit.
  • Function is called after main().

<function_name>

  • <function_name> must be a previously declared function that takes no arguments and returns void.
  • It should be declared as –
void func(void);
  • The function name must be defined (or declared) before the pragma line is reached.

[priority]

0    = Highest priority
0-63 = Used by C libraries
64   = First available user priority
100  = Default priority
255  = Lowest priority

Note :

  1. The optional priority parameter is an integer in the range 64 to 255.
  2. Do not use priorities from 0 to 63.
  3. 0-63 are used by the C libraries.
  4. Functions with higher priorities are called first at startup and last at exit.

Live Example

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

void School();
void College() ;

#pragma startup School 105
#pragma startup College
#pragma exit College
#pragma exit School 105

void main(){
printf("\nI am in main");
getch();
}

void School(){
printf("\nI am in School");
getch();
}

void College(){
printf("\nI am in College");
getch();
}

Output :

I am in College
I am in School
I am in main
I am in School
I am in College

#pragma directive in C : Implementation-specific directives

#pragma directive in C : Implementation-specific directives

Syntax:

#pragma <directive name>

Explanation :

  1. With #pragma, Turbo C++ can define whatever directives it desires without interfering with other compilers that support #pragma.
  2. If the compiler doesn’t recognize <directive name>, it ignores the #pragma directive without an error or warning message.

Turbo C++ supports the following #pragma directives:

#pragma argsused
#pragma exit
#pragma hdrfile
#pragma hdrstop
#pragma inline
#pragma option
#pragma saveregs
#pragma startup
#pragma warn

#undef : Undefine Macro (Preprocessor Directive in C Programming)

#undef : Preprocessor Directive in C Programming

Syntax:

#undef <identifier>

#undef : Undefines a symbol

Undefines a symbol specified by <identifier> which was previously defined with a #define directive.

  • #undef Directive is used to undefine any Macro Symbol.
  • #undef can undefine only “User Defined” Macro’s.
  • #undef cannot undefine “Global Macro Identifiers“.
  • #undef is used where we have to redefine any Macro Identifier.
#include<stdio.h>
#define TEMP 10

#ifdef TEMP
  #undef TEMP
  #define TEMP 75
#else
  #define TEMP 100
#endif

int main()
{
   printf("%d",TEMP);
return 0;
}

Output :

75

Explanation :

  1. TEMP is macro name is defined with value 10.
  2. TEMP is undefined and re-defined with new value as 75.
  3. Since macro constant TEMP has already defined.
  4. #ifdef condition is true.
  5. Directive #undef will undefined the macro constant TEMP but #define will again define symbol TEMP.

#ifndef statement : Conditional Compilation Directives (C Preprocessor)

#ifndef statement : Conditional Compilation Directives (C Preprocessor)

What it does ?

  • These Conditional Compilation Directives allow us to include certain portion of the code depending upon the output of constant expression
  • Block is Called as Conditional Group

Syntax :

#ifndef MACRONAME 
    Statement_block;
#endif

Explanation :

  1. If the MACRONAME specified after #ifndef is not defined previously in #define then statement_block is followed otherwise it is skipped
  2. We say that the conditional succeeds if MACRO is not defined, fails if it is not.

Live Example 1 :

#include"stdio.h"

void main()
{
// Define another macro if MACRO NUM is defined 

#ifndef NUM
      #define MAX 20 
#endif

printf("MAX number is : %d",MAX);
}

Output :

MAX Number is 20

Live Example 2 :

#include<stdio.h>
#define MAX 90

void main()
{
#ifndef MAX
      #define MIN 90
#else
      #define MIN 100
#endif

printf("MIN number : %d",MIN);

}

Output :

MIN number : 100

Rules :

  1. The MACRONAME inside of a conditional can include preprocessing directives.
  2. They are executed only if the conditional succeeds.
  3. You can nest conditional groups inside other conditional groups, but they must be completely nested.
  4. You cannot start a conditional group in one file and end it in another.

#ifdef statement : Conditional Compilation Directives (C Preprocessor)

#ifdef statement : Conditional Compilation Directives (C Preprocessor)


What it does ?

  • These Conditional Compilation Directives allow us to include certain portion of the code depending upon the output of constant expression
  • Block is Called as Conditional Group

Syntax :

#ifdef MACRONAME 
    Statement_block;
#endif

Explanation :

  1. If the MACRONAME specified after #ifdef is defined previously in #define then statement_block is followed otherwise it is skipped
  2. We say that the conditional succeeds if MACRO is defined, fails if it is not.

Live Example 1 :

#include<stdio.h>
#define NUM 10

void main()
{
// Define another macro if MACRO NUM is defined

#ifdef NUM
      #define MAX 20 
#endif

printf("MAX number is : %d",MAX);
}

Output :

MAX Number is 20

Live Example 2 :

#include<stdio.h>

void main()
{

#ifdef MAX 
    #define MIN 90
#else
    #define MIN 100
#endif

printf("MIN number : %d",MIN);
}

Output :

MIN number : 100

Rules :

  1. The MACRONAME inside of a conditional can include preprocessing directives.
  2. They are executed only if the conditional succeeds.
  3. You can nest conditional groups inside other conditional groups, but they must be completely nested.
  4. You cannot start a conditional group in one file and end it in another.

Live Example 3

#include<stdio.h>

int main(){

#ifdef __DATE__
         printf("%s",__DATE__);
    #else
         printf("__DATE__ is not defined");
    #endif

return 0;
}

Output :

Current Date is Printed
  • __DATE__ is global identifier defined in <stdio.h> header file.
  • When we include <stdio.h> header file , at the same time __DATE__ gets included in C Program.

#elif statement : Conditional Compilation Directives (C Preprocessor)

#elif statement : Conditional Compilation Directives (C Preprocessor)

What it does ?

  • These Conditional Compilation Directives allow us to include certain portion of the code depending upon the output of constant expression

Syntax :

#if Expression1
   Statement_block 1;
#elif Expression2
   Statement_block 2;
#elif Expression3
   Statement_block 3;
#else
   Statement_block 4;
#endif

Explanation :

  1. Expression allows  only constant expression
  2. #elif directive means “else if”
  3. #elif Establishes an if-else-if chain for multiple compilation options.
  4. Result of the Expression is TRUE , then Block of Statement between #if and fist #elif is compiled , then it jumps to #endif.
  5. Result of the Expression is FALSE , then Corresponding #elif condition  is tested , if true the the block followed by that elif is Compiled otherwise it checks for Next condition followed by next elif statement
  6. #endif is the end of #if statement

Live Example 1 :

#include<stdio.h>
#define NUM 10

void main()
{
#if(NUM == 0)
       printf("\nNumber is Zero");
#elif(NUM > 0)
       printf("\nNumber is Positive");
#else
       printf("\nNumber is Negative");
#endif
}

Output :

Number is Positive

Live Example 2 :

#include<stdio.h>
#define MARKS 71

void main()
{
#if(MARKS >= 70)
      printf("\nDistinction");
#elif((MARKS >= 60)&&(MARKS < 70 )
      printf("\nFirst Class");
#elif((MARKS >= 40)&&(MARKS < 60 )
      printf("\nSecond Class");
#else
      printf("\nFail");
#endif
}

Output :

Distinction

What is Constant Expression ?

Expression whose result is Constant Number is called Constant Expression

Example : Constant Expression

  1. 190 + 20
  2. 190 / 52 + 4
  3. (356 + 44 * 2 )

Example : Non Constant Expression

  1. y + 270
  2. 130 / v + 44
  3. (546 + y * 22 )

Note : Expression which contain Variable is non Constant Expression