C Preprocessor Operator: defined

In this video tutorial lets see how to use preprocessor operator “defined” in C programming language.

How Does ‘defined’ preprocessor operator work?

defined preprocessor operator can only be used with #if and #elif directives.

If the Macro name passed to define is actually defined, then it returns true or else it’ll return false.

Syntac of “defined”

#if( defined(macro_name1) )
  // Some Set of Code
#elif( defined(macro_name2) )
  // Some More Set of Code
#endif

OR

#if defined(macro_name1) 
  // Some Set of Code
#elif defined(macro_name2) 
  // Some More Set of Code
#endif

Video Tutorial: C Preprocessor Operator: defined


[youtube https://www.youtube.com/watch?v=IDiV22rMPBk]

YouTube Link: https://www.youtube.com/watch?v=IDiV22rMPBk [Watch the Video In Full Screen.]

Source Code: C Preprocessor Operator: defined

#include<stdio.h>

#define PI 3.14159265358979323846

#define AREA

void area_circle(float r);
void circumference_circle(float r);

int main()
{
    float r;

    printf("Enter radius of Circle\n");
    scanf("%f", &r);

    #if defined(AREA)
        area_circle(r);
    #elif defined(CIRCUM)
        circumference_circle(r);
    #else
        printf("Code To Be Implemented\n");

    #endif // defined

    return 0;
}

void area_circle(float r)
{
    printf("Area of Circle is %f\n", (PI * r * r) );
}

void circumference_circle(float r)
{
    printf("Circumference of Circle is %f\n", (2 * PI * r) );
}

Output:
Enter radius of Circle
5
Area of Circle is 78.539816

In above source code AREA macro template or macro name is defined. So defined(AREA) returns true in #if condition. Hence the code inside #if block gets compiled and executed.

#include<stdio.h>

#define PI 3.14159265358979323846

#define CIRCUM

void area_circle(float r);
void circumference_circle(float r);

int main()
{
    float r;

    printf("Enter radius of Circle\n");
    scanf("%f", &r);

    #if defined(AREA)
        area_circle(r);
    #elif defined(CIRCUM)
        circumference_circle(r);
    #else
        printf("Code To Be Implemented\n");

    #endif // defined

    return 0;
}

void area_circle(float r)
{
    printf("Area of Circle is %f\n", (PI * r * r) );
}

void circumference_circle(float r)
{
    printf("Circumference of Circle is %f\n", (2 * PI * r) );
}

Output:
Enter radius of Circle
5
Circumference of Circle is 31.415927

Here macro name AREA is not defined, hence code inside #if gets skipped. Whereas macro CIRCUM is defined, so the code inside #elif gets compiled and executed.

If neither AREA and nor CIRCUM is defined, then code inside #else block gets compiled and executed.

For list of all c programming interviews / viva question and answers visit: C Programming Interview / Viva Q&A List

For full C programming language free video tutorial list visit:C Programming: Beginner To Advance To Expert

Conditional Compilation In C: #if #elif #else #endif

In this video tutorial lets learn about preprocessor command or directives like #if, #elif, #else and #endif. These directives are used in conditional compilation.

Related Read:
Logical Operators In C
Conditional Compilation In C: #ifdef #else #endif

How Does #if and #elif Work?

The block of code inside #if block works only if the condition or the expression in resolved to non-zero number. If the expression is resolved to zero, then the code inside #if is skipped from compilation.

Same is true for #elif: If the condition or the expression is resolved to 0 then the code inside #elif block is skipped from compilation. If it’s resolved to non-zero number then the block of code inside #elif gets compiled and executed.

#else is optional and when used, it should be present only once between #if and #endif, and it should be present at the end(just before the #endif directive). If none of the conditions in #if and #elif match, then the code inside #else directive block gets executed.

#elif is also optional. But it can be used any number of times inside #if and #endif. But it should always be written after #if and not before it. It should be present before #else and not after #else directive.

Note: We can have nested #if #elif #else #endif inside #if and/or #elif and/or #else block. Nesting can go any number or depth.
But remember to have #endif for every #if.

Video Tutorial: Conditional Compilation In C: #if #elif #else #endif


[youtube https://www.youtube.com/watch?v=0s-y4WADkf0]

YouTube Link: https://www.youtube.com/watch?v=0s-y4WADkf0 [Watch the Video In Full Screen.]

When To Use #if, #elif, #else and #endif?

1. When you want certain code to be skipped: #if or #elif or #else part of the code is compiled and executed only when the conditions are met.

2. To write portable code: Again, like that of in #ifdef and #else, we could write portable code. That is, we can write code for specific devices in #if, #elif and #else part and the compiler compiles the code specific to that device. All other code will be treated as comments.

3. Saving memory and file size: We could use it in big projects. We could include device specific files inside #if, #elif and #else blocks depending upon the condition. This way we could avoid including or importing all the files into our source code.

#include<stdio.h>

int main()
{
    #if MARKS
        printf("GRADE A\n");
    #endif // MARKS

    printf("Your Result\n");

    return 0;
}

Output:
Your Result

Here macro template is not even defined. And for #if to resolve and print the code inside its block, MARKS should be evaluated to non-zero number.

#include<stdio.h>

#define MARKS

int main()
{
    #if MARKS
        printf("GRADE A\n");
    #endif // MARKS

    printf("Your Result\n");

    return 0;
}

Output:
Your Result

Here even though MARKS is defined, it doesn’t have a non-zero value, so the code inside #if block isn’t compiled.

#include<stdio.h>

#define MARKS 50

int main()
{
    #if MARKS
        printf("GRADE A\n");
    #endif // MARKS

    printf("Your Result\n");

    return 0;
}

Output:
GRADE A
Your Result

Here MARKS has a macro expansion as 50, which not zero, so code inside #if gets compiled and executed.

Using logical operatation

#include<stdio.h>

#define MARKS 50

int main()
{
    #if(MARKS <= 100 && MARKS >= 80)
        printf("GRADE A\n");
    #endif // MARKS

    printf("Your Result\n");

    return 0;
}

Output:
GRADE A
Your Result

Check the condition for #if. We can use logical operator and/or arithmetic operators and/or relational operators and/or Conditional Operators in the condition.

Nesting of Directives

#include<stdio.h>

#define MARKS 50

int main()
{
    #if(MARKS <= 100)
        printf("GRADE A\n");
        #if(MARKS >= 80)
            printf("You're excellent!\n");
        #else
            printf("You're not that excellent yet!\n");
        #endif
    #endif // MARKS

    printf("Your Result\n");

    return 0;
}

Output:
GRADE A
You’re not that excellent yet!
Your Result

We can nest any number of #if #endif and/or #if #else #endif and/or #if #elif #endif and/or #if #elif #else #endif inside #if and/or #elif and/or #else.

Source Code: Conditional Compilation In C: #if #elif #else #endif

#include<stdio.h>

#define MARKS 50

int main()
{
    #if(MARKS <= 100 && MARKS >= 80)
        printf("GRADE A\n");
    #elif(MARKS <= 79 && MARKS >= 60)
        printf("GRADE B\n");
    #elif(MARKS <= 59 && MARKS >= 40)
        printf("GRADE C\n");
    #elif(MARKS <= 39 && MARKS >= 30)
        printf("GRADE D\n");
    #else
        printf("Please retake the test!\n");
    #endif // MARKS

    printf("Your Result\n");

    return 0;
}

Output:
GRADE C
Your Result

Only 1 block of code is compiled and executed here, even if multiple conditions are satisfying. Whichever condition returns non-zero number first, the code inside its block gets executed. All other code will be skipped.

For list of all c programming interviews / viva question and answers visit: C Programming Interview / Viva Q&A List

For full C programming language free video tutorial list visit:C Programming: Beginner To Advance To Expert

Conditional Compilation In C: #ifdef #else #endif

In this video tutorial lets learn about preprocessor command or directives like #ifdef, #else and #endif. These directives are used for conditional compilation.

How Does #ifdef Work?

The block of code between #ifdef and #endif works only if the macro name is defined orelse the compiler will skip the entire block of code from compiling.

When To Use #ifdef

1. When we want the compiler to skip certain part of the source code: For this we could even use multi-line comment, but if we already had multi-line comments in the code, we can’t enclose the source code and multi-line comments with another multi-line comment. Nesting of multi-line comments are not allowed in C programming language. So instead of commenting the code we could make use of #ifdef directive.

2. To write portable code: For example, we could write code both for iOS and non-iOS devices. Using #ifdef we could check the device OS and based on that deliver specific set of codes. For this we can use #ifdef

Video Tutorial: Conditional Compilation In C: #ifdef #else #endif


[youtube https://www.youtube.com/watch?v=J0nWQRqb3Fc]

YouTube Link: https://www.youtube.com/watch?v=J0nWQRqb3Fc [Watch the Video In Full Screen.]

Source Code: Conditional Compilation In C: #ifdef #else #endif

#include<stdio.h>

#define iOS

int main()
{

    #ifdef iOS
        printf("This is iOS Code\n");
    #else
        printf("This is code for Android Devices\n");
    #endif // iOS

    return 0;
}

Output:
This is iOS Code

#include<stdio.h>

int main()
{

    #ifdef iOS
        printf("This is iOS Code\n");
    #else
        printf("This is code for Android Devices\n");
    #endif // iOS

    return 0;
}

Output:
This is code for Android Devices

In above programs, if iOS macro name is defined, then the set of code present inside #ifdef block gets compiled and executed. If macro name iOS is not defined, then the code inside #else block gets compiled and executed.

#include<stdio.h>
#define iOS

int main()
{

    #ifdef iOS
        printf("This is iOS Code\n");
    #endif // iOS

    printf("This is code for all non iOS Devices\n");

    return 0;
}

Output:
This is iOS Code
This is code for all non iOS Devices

#include<stdio.h>

int main()
{

    #ifdef iOS
        printf("This is iOS Code\n");
    #endif // iOS

    printf("This is code for all non iOS Devices\n");

    return 0;
}

Output:
This is code for all non iOS Devices

Note: using #else is optional. You can just use #ifdef and #endif.

This is similar to if else condition, but here the block of code which do not match the criteria doesn’t even get compiled. It’s treated like regular comments.

For list of all c programming interviews / viva question and answers visit: C Programming Interview / Viva Q&A List

For full C programming language free video tutorial list visit:C Programming: Beginner To Advance To Expert

Comments In C Programming Language

In this video tutorial lets learn about using comments in C programming language.

There are 2 types of comments in C program

1. Single Line Comment.
2. Multi-line comment.

Why Do We Need To Use Comments In Source Code?

1. Whenever someone looks at the code, they need not spend much time in understanding the logic and what that code snippet does. Instead they can simply read the comment and understand the purpose of the code snippet.

2. If there is comment at the top of program, anybody can read it and understand the purpose of the program itself. Usually developers display author information, title and the date of writing the program.

3. When there are multiple contributes to the source code, it’s best to have comments to credit the code contributor and also it’ll be helpful for the other contributes to look at the comment and understand the purpose of the code immediately, instead of tracking the logic and understanding it.

4. If we look at our own code after some time, comments will surely help us understand why we wrote the code in the first place!

Video Tutorial: Comments In C Programming Language


[youtube https://www.youtube.com/watch?v=fNu6hAVr6A0]

YouTube Link: https://www.youtube.com/watch?v=fNu6hAVr6A0 [Watch the Video In Full Screen.]

Source Code: Comments In C Programming Language

/*
 * Author: SATISH
 * Link: Technotip.com
 * Language: C Programming
 * Title: Comments In C
 * Multi-author: No
*/
#include<stdio.h>
#define PI 3.14  // Value of PI

int main()
{
    float r = 5.0;

    // Logic to calculate area of circle
    printf("Area of Circle is %f\n", (PI * r *r ));

    /*
       We could go further and
       add more features to this
       program in future.
    */    return 0;
}

Output:
Area of Circle is 78.500000

Single Line Comment
Whatever is written after double forward slash ( // ) in that same line, will be treated as comment.

Multi-Line Comment
Anything written inside a /* and */ is considered multiple comment. Text inside /* and */ can be written in multiple lines and all those things will be considered as comments.

Note: Comments are not executed as part of the program. Comments are not even compiled. They’re present only for the user to read and understand the purpose of the code.

For list of all c programming interviews / viva question and answers visit: C Programming Interview / Viva Q&A List

For full C programming language free video tutorial list visit:C Programming: Beginner To Advance To Expert

Comparing Floating Point Variable With a Value In C Programming

In this video tutorial lets see how we can compare a floating point variable with a constant value, and lets see the result.

Related Read:
Sizeof Operator in C Programming Language
C Program To Convert Decimal Number To Binary Number, using While Loop

The Problem

If you assign 0.7 to a floating point variable num and then inside if condition you check if num == 0.7, it returns false. Because here variable num is of data type float and the constant value 0.7 is considered as double type data.

Comparison

Video Tutorial: Comparing Floating Point Variable With a Value In C Programming


[youtube https://www.youtube.com/watch?v=DXh6TsxLTME]

YouTube Link: https://www.youtube.com/watch?v=DXh6TsxLTME [Watch the Video In Full Screen.]

Source Code: Comparing Floating Point Variable With a Value In C Programming

#include<stdio.h>

int main()
{
    float num = 0.7;

    if(num == 0.7)
        printf("Yes, true\n");
    else
        printf("Not True\n");

    return 0;
}

Output:
Not True

Some of you might get surprised with the result. But there is nothing to be surprised. It’s working the way it is intended to work.

Reason

We need to keep the basics in mind. When we input decimal numbers, it gets converted into Binary number system and then the further calculation occurs.

Now getting back to our problem: value present in floating point variable num is converted to its binary equivalent. But float has 4 bytes of memory storage.

#include<stdio.h>

int main()
{
    float num = 0.7;

    printf("%d\n", sizeof(num));
    printf("%d\n", sizeof(0.7));

    return 0;
}

Output:
4
8

Next the constant value 0.7 is converted into its binary equivalent. Since its data type is double, it has 8 Bytes of memory for storage. Hence it can store higher precision number.

Now the comparison between these two binary number occurs. Inside double, the binary number has more precision compared to floating point variable – due to available memory for each data type.

For Example:

#include<stdio.h>
int main()
{
    float PI = 3.14;
    double M_PI = 3.14159265358979323846;

    if(PI == M_PI)
        printf("YES\n");
    else
        printf("NO\n");

    return 0;
}

Output:
NO

Even though both variable PI and M_PI has value of PI in it, they’re not equal.

Quick Fix

There are 2 quick fixes for this bug:

1. Typecast constant value to float.
2. Declare double type variable instead of floating point variable.

1. Typecast constant value to float.

#include<stdio.h>
int main()
{
    float num = 0.7;

    if(num == 0.7f)
        printf("Yes, true\n");
    else
        printf("Not True\n");

    return 0;
}

Output:
Yes, true

Inside if condition, we’ve converted double value 0.7 into floating point data, by appending f to it.

2. Declare double type variable instead of floating point variable.

#include<stdio.h>

int main()
{
    double num = 0.7;

    if(num == 0.7)
        printf("Yes, true\n");
    else
        printf("Not True\n");

    return 0;
}

Output:
Yes, true

Best Example:

We had written a C program to Find Grade of Steel. One of our reader reported this comparison bug, and we fixed it using above method mentioned in this video.

Purposefully we’ve not altered the old code. We’ve preserved both old and new code, so that people can learn from our mistake. Take a look at: C Program To Find Grade of Steel

For list of all c programming interviews / viva question and answers visit: C Programming Interview / Viva Q&A List

For full C programming language free video tutorial list visit:C Programming: Beginner To Advance To Expert