One line form of if else and looping statements

By: IncludeHelp, on 09 FEB 2017

Many times, there is only one statement to write with conditional and looping statements, as we know that condition or loop body should start with opening brace and end with the closing brace. But sometimes we do not want to use curly braces as it is allowed to do not use curly braces, if there is only one statement as loop or condition body.

So, here I am discussing some of the styles to write one statement with conditional or looping statement using/without using curly braces.

If there is only one statement in if, else, for, while and do (do while loop), there may three styles of writing the statement

Style 1

if(a>b)
{
	printf("a is greater than b\n");
}
else
{
	printf("b is greater than a\n");
}

Style 2

if(a>b)
	printf("a is greater than b\n");
else
	printf("b is greater than a\n");

Style 3

if(a>b) printf("a is greater than b\n");
else 	printf("b is greater than a\n");

Style 1 is better, as it separates the conditions and body of the statements, but if you do not want to use braces, I would recommend, you should use style 3.

It ensures that there is only single statement with the specific condition or loop, if someone inserts any line after this statement, he/she will remember to put braces before and after the statements.


Here is a program, in which we are checking that entered character is an uppercase character, lowercase character, digit or a special character, so consider the curly braces here.

#include <stdio.h>
int main()
{
	char ch;
	
	printf("Enter a character: ");
	ch=getchar();
	
	if(ch>='A' && ch<='Z') printf("Uppercase character\n");
	else if(ch>='a' && ch<='z') printf("Lowercase character\n");
	else if(ch>='0' && ch<='9') printf("Digit\n");
	else printf("Other special character\n");
	
	return 0;
}

Output

First run:
Enter a character: B
Uppercase character 

Second run:
Enter a character: e
Lowercase character 

Third run:
Enter a character: 8
Digit 

Fourth run:
Enter a character: @
Other special character 

Related Tutorials




Comments and Discussions!

Load comments ↻






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