Home » Programming Tips & Tricks » C - Tips & Tricks

How to use Macro instead of 'Equal To' operator to reduce 'Equal To' or 'Assignment' operator confusion in C

By: IncludeHelp, on 17 FEB 2017

Learn: How we can reduce 'Equal To' or 'Assignment' operator confusion in C programming language by using a Macro instead of 'Equal To' operator.

While writing the code, many times we use 'Assignment' Operator (=) instead of 'Equal To' (==) operator, it will not generate any error but it will affect program's result.

Let suppose,
If there are two blocks that contain some statements within block_1 and block_2, if we want to execute block_1 on value of flag is 1, and block_2 if flag is 0.

Example - Using correct operator 'Equal To'

#include <stdio.h>
int main()
{
	int flag=0;
	if(flag==1)
	{
		printf("Block_1\n");
	}
	else
	{
		printf("Block_2\n");
	}
	
	return 0;	
}

Output

Block_2

See the output, the correct block executed here.

Example - Using incorrect operator 'Assignment'

#include <stdio.h>
int main()
{
	int flag=0;
	if(flag=1)
	{
		printf("Block_1\n");
	}
	else
	{
		printf("Block_2\n");
	}
	
	return 0;	
}

Output

Block_1

See the output, an incorrect block executed.
Why?
The statement if(flag=1) is not comparing the value of flag with 1, '=' is an assignment operator and assigning 1 to flag. Thus after evaluating the statement, it will be if(1), that means condition is true and block_1 will be executed.
Here, two things happened wrong: 1) Correct block is not executed and 2) Value of flag is changed.

To reduce this confusion and execute program correctly, we should use a Macro, here is the Macro statement for 'Equal To' operator.

#define EQUAL_TO ==

Comparing values using Macro 'EQUAL_TO'

In this example, we are defining a Macro EQUAL_TO with == and it can be used in any conditional statement.

#include <stdio.h>

#define EQUAL_TO ==
int main()
{
	int flag=0;
	if(flag EQUAL_TO 1)
	{
		printf("Block_1\n");
	}
	else
	{
		printf("Block_2\n");
	}
	
	return 0;	
}

Output

Block_2

See the output, correct block is executed and there will no confusion between '==' and '='.






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.
Learn PCB Designing: PCB DESIGNING TUTORIAL




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.