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!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.