Learn C practically and Get Certified .

Popular Tutorials

Popular examples, reference materials, learn c interactively, c introduction.

  • Getting Started with C
  • Your First C Program

C Fundamentals

  • C Variables, Constants and Literals
  • C Data Types
  • C Input Output (I/O)
  • C Programming Operators

C Flow Control

C if...else statement.

C while and do...while Loop

  • C break and continue

C switch Statement

C goto Statement

  • C Functions
  • C User-defined functions
  • Types of User-defined Functions in C Programming
  • C Recursion
  • C Storage Class

C Programming Arrays

  • C Multidimensional Arrays
  • Pass arrays to a function in C

C Programming Pointers

  • Relationship Between Arrays and Pointers
  • C Pass Addresses and Pointers
  • C Dynamic Memory Allocation
  • C Array and Pointer Examples
  • C Programming Strings
  • String Manipulations In C Programming Using Library Functions
  • String Examples in C Programming

C Structure and Union

  • C structs and Pointers
  • C Structure and Function

C Programming Files

  • C File Handling
  • C Files Examples

C Additional Topics

  • C Keywords and Identifiers
  • C Precedence And Associativity Of Operators
  • C Bitwise Operators
  • C Preprocessor and Macros
  • C Standard Library Functions

C Tutorials

  • Add Two Integers
  • Find the Largest Number Among Three Numbers
  • Check Whether a Number is Even or Odd

C if Statement

The syntax of the if statement in C programming is:

How if statement works?

The if statement evaluates the test expression inside the parenthesis () .

  • If the test expression is evaluated to true, statements inside the body of if are executed.
  • If the test expression is evaluated to false, statements inside the body of if are not executed.

How if statement works in C programming?

To learn more about when test expression is evaluated to true (non-zero value) and false (0), check relational and logical operators .

Example 1: if statement

When the user enters -2, the test expression number<0 is evaluated to true. Hence, You entered -2 is displayed on the screen.

When the user enters 5, the test expression number<0 is evaluated to false and the statement inside the body of if is not executed

The if statement may have an optional else block. The syntax of the if..else statement is:

How if...else statement works?

If the test expression is evaluated to true,

  • statements inside the body of if are executed.
  • statements inside the body of else are skipped from execution.

If the test expression is evaluated to false,

  • statements inside the body of else are executed
  • statements inside the body of if are skipped from execution.

How if...else statement works in C programming?

Example 2: if...else statement

When the user enters 7, the test expression number%2==0 is evaluated to false. Hence, the statement inside the body of else is executed.

C if...else Ladder

The if...else statement executes two different codes depending upon whether the test expression is true or false. Sometimes, a choice has to be made from more than 2 possibilities.

The if...else ladder allows you to check between multiple test expressions and execute different statements.

Syntax of if...else Ladder

Example 3: c if...else ladder.

  • Nested if...else

It is possible to include an if...else statement inside the body of another if...else statement.

Example 4: Nested if...else

This program given below relates two integers using either < , > and = similar to the if...else ladder's example. However, we will use a nested if...else statement to solve this problem.

If the body of an if...else statement has only one statement, you do not need to use brackets {} .

For example, this code

is equivalent to

Table of Contents

  • if Statement
  • if...else Statement
  • if...else Ladder

Before we wrap up, let’s put your knowledge of C if else to the test! Can you solve the following challenge?

Write a function to determine if a student has passed or failed based on their score.

  • A student passes if their score is 50 or above.
  • Return "Pass" if the score is 50 or above and "Fail" otherwise.
  • For example, with input 55 , the return value should be "Pass" .

Video: C if else Statement

Sorry about that.

Our premium learning platform, created with over a decade of experience and thousands of feedbacks .

Learn and improve your coding skills like never before.

  • Interactive Courses
  • Certificates
  • 2000+ Challenges

Related Tutorials

CProgramming Tutorial

  • C Programming Tutorial
  • Basics of C
  • C - Overview
  • C - Features
  • C - History
  • C - Environment Setup
  • C - Program Structure
  • C - Hello World
  • C - Compilation Process
  • C - Comments
  • C - Keywords
  • C - Identifiers
  • C - User Input
  • C - Basic Syntax
  • C - Data Types
  • C - Variables
  • C - Integer Promotions
  • C - Type Conversion
  • C - Type Casting
  • C - Booleans
  • Constants and Literals in C
  • C - Constants
  • C - Literals
  • C - Escape sequences
  • C - Format Specifiers
  • Operators in C
  • C - Operators
  • C - Arithmetic Operators
  • C - Relational Operators
  • C - Logical Operators
  • C - Bitwise Operators
  • C - Assignment Operators
  • C - Unary Operators
  • C - Increment and Decrement Operators
  • C - Ternary Operator
  • C - sizeof Operator
  • C - Operator Precedence
  • C - Misc Operators
  • Decision Making in C
  • C - Decision Making
  • C - if statement
  • C - if...else statement
  • C - nested if statements
  • C - switch statement
  • C - nested switch statements
  • C - While loop
  • C - For loop
  • C - Do...while loop
  • C - Nested loop
  • C - Infinite loop
  • C - Break Statement
  • C - Continue Statement
  • C - goto Statement
  • Functions in C
  • C - Functions
  • C - Main Function
  • C - Function call by Value
  • C - Function call by reference
  • C - Nested Functions
  • C - Variadic Functions
  • C - User-Defined Functions
  • C - Callback Function
  • C - Return Statement
  • C - Recursion
  • Scope Rules in C
  • C - Scope Rules
  • C - Static Variables
  • C - Global Variables
  • Arrays in C
  • C - Properties of Array
  • C - Multi-Dimensional Arrays
  • C - Passing Arrays to Function
  • C - Return Array from Function
  • C - Variable Length Arrays
  • Pointers in C
  • C - Pointers
  • C - Pointers and Arrays
  • C - Applications of Pointers
  • C - Pointer Arithmetics
  • C - Array of Pointers
  • C - Pointer to Pointer
  • C - Passing Pointers to Functions
  • C - Return Pointer from Functions
  • C - Function Pointers
  • C - Pointer to an Array
  • C - Pointers to Structures
  • C - Chain of Pointers
  • C - Pointer vs Array
  • C - Character Pointers and Functions
  • C - NULL Pointer
  • C - void Pointer
  • C - Dangling Pointers
  • C - Dereference Pointer
  • C - Near, Far and Huge Pointers
  • C - Initialization of Pointer Arrays
  • C - Pointers vs. Multi-dimensional Arrays
  • Strings in C
  • C - Strings
  • C - Array of Strings
  • C - Special Characters
  • C Structures and Unions
  • C - Structures
  • C - Structures and Functions
  • C - Arrays of Structures
  • C - Self-Referential Structures
  • C - Lookup Tables
  • C - Dot (.) Operator
  • C - Enumeration (or enum)
  • C - Structure Padding and Packing
  • C - Nested Structures
  • C - Anonymous Structure and Union
  • C - Bit Fields
  • C - Typedef
  • File Handling in C
  • C - Input & Output
  • C - File I/O (File Handling)
  • C Preprocessors
  • C - Preprocessors
  • C - Pragmas
  • C - Preprocessor Operators
  • C - Header Files
  • Memory Management in C
  • C - Memory Management
  • C - Memory Address
  • C - Storage Classes
  • Miscellaneous Topics
  • C - Error Handling
  • C - Variable Arguments
  • C - Command Execution
  • C - Math Functions
  • C - Static Keyword
  • C - Random Number Generation
  • C - Command Line Arguments
  • C Programming Resources
  • C - Questions & Answers
  • C - Quick Guide
  • C - Cheat Sheet
  • C - Useful Resources
  • C - Discussion
  • Selected Reading
  • UPSC IAS Exams Notes
  • Developer's Best Practices
  • Questions and Answers
  • Effective Resume Writing
  • HR Interview Questions
  • Computer Glossary

C - Nested If Statements

It is always legal in C programming to nest if-else statements, which means you can use one if or else-if statement inside another if or else-if statement(s) .

In the programming context, the term "nesting" refers to enclosing a particular programming element inside another similar element. For example, nested loops, nested structures, nested conditional statements, etc. If an if statement in C is employed inside another if statement, then we call it as a nested if statement in C.

The syntax of nested if statements is as follows −

The following flowchart represents the nesting of if statements −

Nested Condition

You can compound the Boolean expressions with && or || to get the same effect. However, for more complex algorithms, where there are different combinations of multiple Boolean expressions, it becomes difficult to form the compound conditions. Instead, it is recommended to use nested structures.

Another if statement can appear inside a top-level if block, or its else block, or inside both.

Let us take an example, where the program needs to determine if a given number is less than 100, between 100 to 200, or above 200. We can express this logic with the following compound Boolean expression −

Run the code and check its output. Here, we have intialized the value of "a" as 274. Change this value and run the code again. If the supplied value is less than 100, then you will get a different output. Similarly, the output will change again if the supplied number is in between 100 and 200.

Now let's use nested conditions for the same problem. It will make the solution more understandable when we use nested conditions.

First, check if "a >= 100". Inside the true part of the if statement, check if it is <200 to decide if the number lies between 100-200, or it is >200. If the first condition (a >= 100) is false, it indicates that the number is less than 100.

Run the code and check its output. You will get different outputs for different input values of "a" −

The following program uses nested if statements to determine if a number is divisible by 2 and 3, divisible by 2 but not 3, divisible by 3 but not 2, and not divisible by both 2 and 3.

Run the code and check its output −

For different values of "a", you will get different outputs.

Given below is a C program to check if a given year is a leap year or not. Whether the year is a leap year or not is determined by the following rules −

  • Is the year divisible by 4?
  • If yes, is it a century year (divisible by 100)?
  • If yes, is it divisible by 400? If yes, it is a leap year, otherwise not.
  • If it is divisible by 4 and not a century year, it is a leap year.
  • If it is not divisible by 4, it is not a leap year.

Here is the C code −

Test the program with different values for the variable "year" such as 1900, 2023, 2000, 2012.

The same result can be achieved by using the compound Boolean expressions instead of nested if statements, as shown below −

With nested if statements in C, we can write structured and multi-level decision-making algorithms. They simplify coding the complex discriminatory logical situations. Nesting too makes the program more readable, and easy to understand.

If Statement in C – How to use If-Else Statements in the C Programming Language

Dionysia Lemonaki

In the C programming language, you have the ability to control the flow of a program.

In particular, the program is able to make decisions on what it should do next. And those decisions are based on the state of certain pre-defined conditions you set.

The program will decide what the next steps should be based on whether the conditions are met or not.

The act of doing one thing if a particular condition is met and a different thing if that particular condition is not met is called control flow .

For example, you may want to perform an action under only a specific condition. And you may want to perform another action under an entirely different condition. Or, you may want to perform another, completely different action when that specific condition you set is not met.

To be able to do all of the above, and control the flow of a program, you will need to use an if statement.

In this article, you will learn all about the if statement – its syntax and examples of how to use it so you can understand how it works.

You will also learn about the if else statement – that is the else statement that is added to the if statement for additional program flexibility.

In addition, you will learn about the else if statement for when you want to add more choices to your conditions.

Here is what we will cover:

  • How to create an if statement in C
  • What is an example of an if statement?
  • What is an example of an if else statement?
  • What is an example of an else if statement?

What Is An if Statement In C?

An if statement is also known as a conditional statement and is used for decision-making. It acts as a fork in the road or a branch.

A conditional statement takes a specific action based on the result of a check or comparison that takes place.

So, all in all, the if statement makes a decision based on a condition.

The condition is a Boolean expression. A Boolean expression can only be one of two values – true or false.

If the given condition evaluates to true only then is the code inside the if block executed.

If the given condition evaluates to false , the code inside the if block is ignored and skipped.

How To Create An if statement In C – A Syntax Breakdown For Beginners

The general syntax for an if statement in C is the following:

Let's break it down:

  • You start an if statement using the if keyword.
  • Inside parentheses, you include a condition that needs checking and evaluating, which is always a Boolean expression. This condition will only evaluate as either true or false .
  • The if block is denoted by a set of curly braces, {} .
  • Inside the if block, there are lines of code – make sure the code is indented so it is easier to read.

What Is An Example Of An if Statement?

Next, let’s see a practical example of an if statement.

I will create a variable named age that will hold an integer value.

I will then prompt the user to enter their age and store the answer in the variable age .

Then, I will create a condition that checks whether the value contained in the variable age is less than 18.

If so, I want a message printed to the console letting the user know that to proceed, the user should be at least 18 years of age.

I compile the code using gcc conditionals.c , where gcc is the name of the C compiler and conditionals.c is the name of the file containing the C source code.

Then, to run the code I type ./a.out .

When asked for my age I enter 16 and get the following output:

The condition ( age < 18 ) evaluates to true so the code in the if block executes.

Then, I re-compile and re-run the program.

This time, when asked for my age, I enter 28 and get the following output:

Well... There is no output.

This is because the condition evaluates to false and therefore the body of the if block is skipped.

I have also not specified what should happen in the case that the user's age is greater than 18.

I could write another if statement that will print a message to the console if the user's age is greater than 18 so the code is a bit clearer:

I compile and run the code, and when prompted for my age I enter again 28:

This code works. That said, there is a better way to write it and you will see how to do that in the following section.

What Is An if else Statement in C?

Multiple if statements on their own are not helpful – especially as the programs grow larger and larger.

So, for that reason, an if statement is accompanied by an else statement.

The if else statement essentially means that " if this condition is true do the following thing, else do this thing instead".

If the condition inside the parentheses evaluates to true , the code inside the if block will execute. However, if that condition evaluates to false , the code inside the else block will execute.

The else keyword is the solution for when the if condition is false and the code inside the if block doesn't run. It provides an alternative.

The general syntax looks something like the following:

What Is An Example Of An if else Statement?

Now, let's revisit the example with the two separate if statements from earlier on:

Let's re-write it using an if else statement instead:

If the condition is true the code in the if block runs:

If the condition is false the code in the if block is skipped and the code in the else block runs instead:

What Is An else if Statement?

But what happens when you want to have more than one condition to choose from?

If you wish to chose between more than one option and want to have a greater variety in actions, then you can introduce an else if statement.

An else if statement essentially means that "If this condition is true, do the following. If it isn't, do this instead. However, if none of the above is true and all else fails, finally do this."

What Is An Example Of An else if Statement?

Let's see how an else if statement works.

Say you have the following example:

If the first if statement is true, the rest of the block will not run:

If the first if statement is false, then the program moves on to the next condition.

If that is true the code inside the else if block executes and the rest of the block doesn't run:

If both of the previous conditions are all false, then the last resort is the else block which is the one to execute:

And there you have it – you now know the basics of if , if else , and else if statements in C!

I hope you found this article helpful.

To learn more about the C programming language, check out the following free resources:

  • C Programming Tutorial for Beginners
  • What is The C Programming Language? A Tutorial for Beginners
  • The C Beginner's Handbook: Learn C Programming Language basics in just a few hours

Thank you so much for reading and happy coding :)

Read more posts .

If this article was helpful, share it .

Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started

PrepBytes Blog

ONE-STOP RESOURCE FOR EVERYTHING RELATED TO CODING

Sign in to your account

Forgot your password?

Login via OTP

We will send you an one time password on your mobile number

An OTP has been sent to your mobile number please verify it below

Register with PrepBytes

Nested if else statement in c.

' src=

Last Updated on March 2, 2023 by Prepbytes

assignment within if statement c

In this article, we are going to explore nested if-else statement in c with syntax, flowcharts, and example. We will also look at nested if statement in c with syntax and example. At the end of the article, we will discuss some advantages and disadvantages of using nested if-else statements.

Introduction to If-Else Statement

In programming, if-else statements are used to make alternative conclusions based on particular criteria being met. Because of this, these statements are referred to be decision-making statements. They aid in making judgments based on conditions and hence contribute to determining the flow of the code.

If the condition contained within the if bracket is true, the statements contained within the if bracket is executed. If the condition is found to be false, the if block is bypassed and the statements inside the otherwise block are executed.

For example, given a number, we must determine if it is prime or not. That means we must decide whether to print prime or not prime. This is why we use the if-else statement in c.

Nested If Else Statement

We’ve already seen how useful if and else statements are, but what if we need to check for more conditions even if one is met?

For example, if we need to determine whether a number is even or odd and if it is even, whether it is divisible by 8 or not, and if it is odd, whether it is divisible by 7 or not. In this scenario, a single if-else statement would be insufficient.

To begin, we will use one if-else statement to determine whether the integer is even or odd. Then, in the if block, if the number was even, we’d have to include another if and else statement to see if it’s divisible by 8 or not.

Similarly, in the else block, we would need to include another if and else statement to determine whether the integer is divisible by 7.

Nesting is the practice of including multiple if-else statements within an if and else statement. The second set of if and else statements is considered to be nested within the first.

This is why the C language supports the nesting of if and else expressions. These are known as nested if-else statements, and they allow for more precise decision-making when additional requirements must be tested within the first conditions, like in the prior example.

Syntax of Nested If-Else Statement

Let us see the syntax of nested if-else statements in c:

Flow Chart of Nested If-Else

assignment within if statement c

Elaboration In the preceding example, the first IF statement checks to see if n is even. If this n is even, condition 1 evaluates to true, and we proceed inside the if block. Here is our nested if-else statement, which checks to see if n is divisible by 8. If condition 2 returns true, we proceed to execute line 1. We print here that the integer is even and divisible by 8. If condition 2 is false, we enter the else statement and print that the number is even but not divisible by 8.

Similarly, if condition 1 evaluates to false, we skip to the ELSE block and check the condition of the nested if statement. We enter the nested if condition 3 evaluates to true. We print here that the number is odd and divisible by 7. If condition 3 is false, we enter the nested else statement and print that the number is odd but not divisible by 7.

The important thing to remember here is that when we enter the if block, the otherwise block is ignored, and when we enter the else block, the if block is ignored, and this is exactly what happens.

Above, we go through an example of a nested if-else statement in c. Let’s see the code implementation of the above example in c.

Code Implementation of Nested If-Else:

Nested if statement in c.

In C, a nested if statement is a construct where an if statement is placed inside another if statement. The inner if statement is only evaluated if the condition of the outer if statement is true.

It is also possible to have multiple nested if statements, where each inner if statement is executed only if the outer if statement’s condition is true.

Nested-if statements can be helpful when you have multiple conditions to check, and the conditions are dependent on each other. It can simplify complex conditions and improve the readability and efficiency of the code. However, it’s important to use them judiciously, as overuse of nested if statements can make code more complex, harder to read, harder to debug and increase execution time and memory usage.

Syntax of Nested If Statement

the inner if statement will only be executed if the outer if statement’s condition (condition1) is true. If condition 1 is false, the program will skip over the inner if statement and the control flow will continue with the next statement after the nested if statement.

Advantages of using Nested If-Else Statement

There are several advantages to using nested if-else statement in C:

  • Improved readability: Nesting if-else statement can make code more readable by making it clear which conditions must be met in order for certain actions to be taken.
  • Handling multiple conditions: Nesting if-else statement allows you to handle multiple conditions at once, which can be useful when the conditions are dependent on each other.
  • Reusability: Nesting if-else statement can help to make code more reusable by allowing you to use the same conditions in multiple places within your code.
  • Improved efficiency: By using nested if-else statement, you can improve the efficiency of your code by only executing certain statements if the conditions are met.
  • Simplify complex conditions: By breaking down complex conditions into multiple nested if-else statement, it makes it easier to understand and debug the code.

It’s worth noting that, while nested if-else statement can be useful in certain situations, they can also make code more difficult to read and understand if overused or used in a confusing way. So it’s important to use them judiciously.

Disadvantages of using Nested If-Else Statement

There are several disadvantages to using nested if-else statement in c:

  • Increased complexity: Nesting if-else statement can make code more complex, which can make it more difficult to understand and debug.
  • Decreased readability: Nesting if-else statement can make code less readable, especially if there are multiple levels of nesting.
  • Increased likelihood of bugs: With increased complexity and decreased readability, the likelihood of bugs in the code also increases.
  • Hard to maintain: When the requirements of the program change, it’s hard to maintain the code and make necessary updates, especially when there are multiple levels of nesting.
  • Decreased performance: Nesting an if-else statement can decrease the performance of your code because the program has to evaluate multiple conditions.

It’s worth noting that, while nested if-else statement can be useful in certain situations, they can also make code more difficult to read and understand if overused or used in a confusing way. So it’s important to use them judiciously and try to avoid excessive nesting.

  • Nested if-else statement in C is a construct where an if-else statement is placed inside another if-else statement.
  • The inner if-else statement is executed only if the outer if-else statement’s condition is true.
  • Nested if-else statement in C can be useful when handling multiple conditions that are dependent on each other and make code more readable.
  • Overuse of nested if-else statements can make code more complex, harder to read, harder to debug and increase execution time and memory usage.
  • Nested if statements in C are a construct where an if statement is placed inside another if statement.
  • The inner if statement is only evaluated if the condition of the outer if statement is true.
  • Writing if statement within another if is called as nested if statement.

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Save my name, email, and website in this browser for the next time I comment.

  • Linked List
  • Segment Tree
  • Backtracking
  • Dynamic Programming
  • Greedy Algorithm
  • Operating System
  • Company Placement
  • Interview Tips
  • General Interview Questions
  • Data Structure
  • Other Topics
  • Computational Geometry
  • Game Theory

Related Post

Null character in c, assignment operator in c, ackermann function in c, median of two sorted arrays of different size in c, number is palindrome or not in c, implementation of queue using linked list in c.

01 Career Opportunities

02 beginner, 03 intermediate, 04 advanced, 05 training programs, conditional statements in c: if, if..else, nested if, free c programming online course with certificate, conditional statements in c: an overview, what are conditional statements in c, why conditional statements, types of conditional statements in c, 1. if … else statements in c, variants of if-else statements in c, if statement in c, if-else statement in c, if else-if ladder in c, nested if…else statement in c.

  • If the nested if condition is false , the else statement in the nested if block gets executed.

2. Switch Statement in C

Syntax of switch statement in c, example of switch statement in c, 3. conditional operator in c, syntax of conditional operator in c, example of conditional operator in c, 4. jump statements in c, syntax of break statement in c, example of break statement in c playground, 2. continue, syntax of continue statement in c, example of continue statement in c, syntax of goto statement in c, example of goto statement in c, syntax of return statement in c, example of return statement in c, live classes schedule.

Filling Fast
Filling Fast
Filling Fast
Filling Fast
Filling Fast
Filling Fast

About Author

C Programming Tutorial

  • if-else statements in C

Last updated on July 27, 2020

Control statements in C #

In all the programs we have written so far statements execute sequentially in the order in which they appear. But sometimes we want statements to execute only when some condition is true For example, If the bank balance is above seven figures buy a new car else renew monthly bus pass. To make such decisions C provides a facility called Control Statements.

Control statements are used to alter the flow of the program. They are used to specify the order in which statements can be executed. They are commonly used to define how control is transferred from one part of the program to another.

C language has following control statements:

  • do... while

Compound statement #

A Compound statement is a block of statement grouped together using braces ( {} ). In a compound statement, all statements are executed sequentially. A compound statement is also known as a block. It takes the following form:

{ statement1; statement2; statement3; ... statementn; }

We have learned that all statements end with a semicolon ( ; ) but the compound statement is an exception to this rule. Another important thing to understand is that a compound statement is syntactically equivalent to a single statement, this means that we can place a compound statement where a single statement is allowed. This means the following code is perfectly valid.

#include<stdio.h> int main() { int i = 100; printf("A single statement\n"); { // a compound statement printf("A statement inside compound statement\n"); printf("Another statement inside compound statement\n"); } // signal to operating system everything works fine return 0; }

Expected Output:

A single statement A statement inside compound statement Another statement inside compound statement

if statement #

If statement is used to test a condition and take one of the two possible actions. The syntax of the if statement is:

if (condition) { // if block statement1; statement2; }

the condition can be any constant, variable, expression, relational expression, logical expression and so on. Just remember that in C, any non-zero value is considered as true while 0 is considered as false.

How it works:

The statements inside the if block (i.e statement1 and statement2 ) are executed only when the condition is true. If it is false then statements inside if the block are skipped. The braces ( {} ) are always required when you want to execute more than one statement when the condition is true. Also, note that the statements inside the if block are slightly indented. This is done to improve readability, indentation is not syntactically required.

If you want to execute only one statement when the condition is true then braces ( {} ) can be omitted. In general, you should not omit the braces even if there is a single statement to execute.

if (condition) statement1;

The following program prints a message if the number entered by the user is even.

#include<stdio.h> int main() { int n; printf("Enter a number: "); scanf("%d", &n); if(n % 2 == 0) { printf("%d is even", n); } // signal to operating system everything works fine return 0; }

Run the program and enter an even number and you will get the following output:

Enter a number: 46 46 is even

Run the program again but this time, enter an odd number.

This time, the condition ( n % 2 == 0 ) evaluates to false, as a result, statement inside the if block is skipped.

Which statement belongs to if? #

if (condition) statement1; statement2; statement3;

Can you find which statement(s) will be omitted if the condition is false?

If there are no braces ( {} ) following the if statement then only the next immediate statement belongs to the if statement. The same thing is true for else and else-if clause (else and else-if clause are discussed later in this chapter).

Therefore, only the statement1 belongs to the if statement. So if the condition is false then only statement1 will be omitted. The statement2 and statement3 will be always executed regardless of the condition. The following example demonstrates this fact:

#include<stdio.h> int main() { if(0) printf("statement 1\n"); printf("statement 2\n"); printf("statement 3\n"); // signal to operating system everything works fine return 0; }
statement 2 statement 3

Here the condition is false, that’s why only the last two statements are executed. This verifies the fact the statement in line 6 only belongs to the if statement. At a glance, it is slightly confusing to determine which statement belongs to the if statement, that’s why it is recommended to always use braces ( {} ) to wrap statements you want to execute with the if statement.

#include<stdio.h> int main() { if(0) { printf("statement 1\n"); } printf("statement 2\n"); printf("statement 3\n"); // signal to operating system prgram ran fine return 0; }

Now you can clearly see that only first statement belongs to the if statement.

The else clause #

The else clause allows us to add an alternative path to the if condition. Statements under the else block are executed only when the if condition is false.

if (condition) { // if block statement1; statement2; } else { // else block statement3; statement4; }

As usual, if you have only one statement in the else block then the braces ( {} ) can be omitted. Although, it is not recommended.

if (expression) statement1; else statement2;

As already said, indentation is not required, so the above code can also be written as:

But why kill the readability? Be a good programmer and always indent our code.

Now, let's add an else clause to our previously written program.

#include<stdio.h> int main() { int n; printf("Enter a number: "); scanf("%d", &n); if(n % 2 == 0) { printf("%d is even", n); } else { printf("%d is odd", n); } // signal to operating system everything program ran fine return 0; }

1st run: Run the program and enter an even number.

Enter a number: 44 44 is even
Enter a number: 91 91 is odd

Consider one more example. The following program determines the larger of the two entered numbers:

#include<stdio.h> int main() { int a, b; printf("Enter two numbers: "); scanf("%d %d", &a, &b); if(a > b) { printf("%d is greater than %d", a, b); } else { printf("%d is greater than %d", b, a); } // signal to operating system everything works fine return 0; }
Enter two numbers: 344 200 344 is greater than 200
Enter two numbers: 99 999 999 is greater than 99

Nesting if… else #

We can add if .. else statement inside if block or else block. This is called nesting of if .. else . Syntax:

if(condition1) { if(condition2) { statement1; statement2; } else { statement3; statement4; } } else { if(condition3) { statement5; statement6; } else { statement7; statement8; } }

We can nest if .. else statement to any depth.

First, the condition1 is checked, if it is true, then the condition2 is checked, if it is true then statements inside the if block (lines 4-7) are executed.

Otherwise, the statements in the else block (lines 10-13) are executed. Otherwise, if the condition1 is false, then the condition3 is checked, if it is true then the statements under the if block in lines 19-22 are executed. Otherwise, the statements in the else block (lines 25-28) are executed.

The following program uses 2 nested if-else statements to determine the larger of the three numbers:

#include<stdio.h> int main() { int a, b, c, larger; printf("Enter three numbers: "); scanf("%d %d %d", &a, &b, &c); if(a > b) { if(a > c) { larger = a; } else { larger = c; } } else { if(b > c) { larger = b; } else { larger = c; } } printf("Largest number is %d", larger); // signal to operating system everything works fine return 0; }
Enter three numbers: 12 35 54 Largest number is 54
Enter three numbers: 77 23 871 Largest number is 871

Matching if.. else parts #

Sometimes it becomes confusing to associate an else clause with the if statement. Consider the following example:

if(a<10) if (a % 2 ==0) printf("a is even and less than 10\n"); else printf("a is greater than 10");

Which if statement is associated with the else block? According to the way code is indented you might think else belongs to the first if statement, but it is not. The compiler does not associate if and else statement according to indentation, it matches the else part with the closest unmatched if part. So the else statement is associated with the second if statement.

We can always avoid such complications using braces ( {} ).

if(a < 10) { if (a % 2 ==0) { printf("a is even and less than 10\n"); } else { printf("a is greater than 10"); } }

Now everything is crystal clear.

else if clause #

if-else is a bi-directional statement that is used to test a condition and take one of the possible two actions. What if we to perform a series of tests? One way to check for multiple conditions is to use the nested if-else statement. We have seen an example of this technique earlier in this chapter. Another way to accomplish this is to use the else-if clause. The else-if clause extends the basic if-else statement and allows us to perform a series of tests. The updated syntax of the if-else statement looks like this:

if(condition1) { statement1; } else if(condition2) { statement2; } else if(condition3) { statement3; } ... else { statement4; }

Here, each condition is checked one by one. As soon as a condition is found to be true then statements corresponding to that block are executed. The conditions and statements in the rest of the if-else statement are skipped and program control comes out of the if-else statement. If none of the conditions is true then statements in the else block are executed.

Using else-if clause we can write nested if-else statement in a more compact form.

Let's rewrite the program to determine the largest of the two numbers using the else-if clause.

#include<stdio.h> int main() { int a, b, c, larger; printf("Enter three numbers: "); scanf("%d %d %d", &a, &b, &c); if(a > b && a > c) { larger = a; } else if(b > a && b > c) { larger = b; } else { larger = c; } printf("Largest number is %d", larger); // signal to operating system everything works fine return 0; }

This version of the program is functionally equivalent to the one that uses nested if-else statement. But it avoids deep indentation making the code more readable.

Load Comments

  • Intro to C Programming
  • Installing Code Blocks
  • Creating and Running The First C Program
  • Basic Elements of a C Program
  • Keywords and Identifiers
  • Data Types in C
  • Constants in C
  • Variables in C
  • Input and Output in C
  • Formatted Input and Output in C
  • Arithmetic Operators in C
  • Operator Precedence and Associativity in C
  • Assignment Operator in C
  • Increment and Decrement Operators in C
  • Relational Operators in C
  • Logical Operators in C
  • Conditional Operator, Comma operator and sizeof() operator in C
  • Implicit Type Conversion in C
  • Explicit Type Conversion in C
  • The while loop in C
  • The do while loop in C
  • The for loop in C
  • The Infinite Loop in C
  • The break and continue statement in C
  • The Switch statement in C
  • Function basics in C
  • The return statement in C
  • Actual and Formal arguments in C
  • Local, Global and Static variables in C
  • Recursive Function in C
  • One dimensional Array in C
  • One Dimensional Array and Function in C
  • Two Dimensional Array in C
  • Pointer Basics in C
  • Pointer Arithmetic in C
  • Pointers and 1-D arrays
  • Pointers and 2-D arrays
  • Call by Value and Call by Reference in C
  • Returning more than one value from function in C
  • Returning a Pointer from a Function in C
  • Passing 1-D Array to a Function in C
  • Passing 2-D Array to a Function in C
  • Array of Pointers in C
  • Void Pointers in C
  • The malloc() Function in C
  • The calloc() Function in C
  • The realloc() Function in C
  • String Basics in C
  • The strlen() Function in C
  • The strcmp() Function in C
  • The strcpy() Function in C
  • The strcat() Function in C
  • Character Array and Character Pointer in C
  • Array of Strings in C
  • Array of Pointers to Strings in C
  • The sprintf() Function in C
  • The sscanf() Function in C
  • Structure Basics in C
  • Array of Structures in C
  • Array as Member of Structure in C
  • Nested Structures in C
  • Pointer to a Structure in C
  • Pointers as Structure Member in C
  • Structures and Functions in C
  • Union Basics in C
  • typedef statement in C
  • Basics of File Handling in C
  • fputc() Function in C
  • fgetc() Function in C
  • fputs() Function in C
  • fgets() Function in C
  • fprintf() Function in C
  • fscanf() Function in C
  • fwrite() Function in C
  • fread() Function in C

Recent Posts

  • Machine Learning Experts You Should Be Following Online
  • 4 Ways to Prepare for the AP Computer Science A Exam
  • Finance Assignment Online Help for the Busy and Tired Students: Get Help from Experts
  • Top 9 Machine Learning Algorithms for Data Scientists
  • Data Science Learning Path or Steps to become a data scientist Final
  • Enable Edit Button in Shutter In Linux Mint 19 and Ubuntu 18.04
  • Python 3 time module
  • Pygments Tutorial
  • How to use Virtualenv?
  • Installing MySQL (Windows, Linux and Mac)
  • What is if __name__ == '__main__' in Python ?
  • Installing GoAccess (A Real-time web log analyzer)
  • Installing Isso

C if & else

last modified January 9, 2023

C if else tutorial shows how to create conditions and branches in C with if/else statements.

There can be multiple if/else statements.

C if else example

In the example we have a simple condition; if the num variable is positive, the message "The number is positive" is printed to the console. Otherwise; nothing is printed.

Now we have added the second branch. The else statement specifies the block that is executed if the if condition fails.

C multiple conditions with else if

We can have multiple branches of conditions with additional else if statements.

We run the example a few times.

In this article, we have covered if else conditions in C.

Stack Exchange Network

Stack Exchange network consists of 183 Q&A communities including Stack Overflow , the largest, most trusted online community for developers to learn, share their knowledge, and build their careers.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Is doing an assignment inside a condition considered a code smell?

Many times I have to write a loop that requires initialization of a loop condition, and an update every time the loop executes. Here's one example:

One things I dislike about this code is the duplicate call to getCurrentStrings() . One option is to add the assignment to the condition as follows:

But while I now have less duplication and less code, i feel that my code is now harder to read. On the other hand, it is easier to understand that we are looping on a variable that may be changed by the loop.

What is the best practice to follow in cases like this?

gnat's user avatar

  • 5 Doing a call like GetCurrentStrings() once outside a while loop, and then calling it inside the loop, is a very common, well understood, accepted as best practice pattern. It's not code duplication; you have to call GetCurrentStrings() once outside the loop to establish the initial condition for the while . –  Robert Harvey Commented Mar 20, 2014 at 15:57

5 Answers 5

First, I would definitely frame the first version as a for-loop:

Unfortunately there's no idiomatic way in C++, Java or C# that I know of to get rid of the duplication between initializer and incrementer. I personally like abstracting the looping pattern into an Iterable or Enumerable or whatever your language provides. But in the end, that just moves the duplication into a reusable place. Here's a C# example:

Now you can do this:

C#'s yield makes writing this easy; it's uglier in Java or C++.

C++ culture is more accepting of assignment-in-condition than the other languages, and implicit boolean conversions are actually used in some idioms, e.g. type queries:

The above relies on the implicit conversion of pointers to bool and is idiomatic. Here's another:

This modifies the variable s within the condition.

The common pattern, however, is that the condition itself is trivial, usually relying completely on some implicit conversion to bool. Since collections don't do that, putting an empty test there would be considered less idiomatic.

C culture is even more accepting, with the fgetc loop idiom looking like this:

But in higher-level languages, this is frowned upon, because with the higher level usually comes lesser acceptance of tricky code.

Community's user avatar

  • Liked the multiple explanations and examples. Thanks! –  vainolo Commented Mar 24, 2014 at 8:28

The fundamental problem here, it seems to me, is that you have a N plus one half loop , and those are always a bit messy to express. In this particular case, you could hoist the "half" part of the loop into the test, as you have done, but it looks very awkward to me. Two ways of expressing that loop may be:

Idiomatic C/C++ in my opinion:

Strict "structured programming", which tends to frown on break :

microtherion's user avatar

  • 1 Indeed, for(;;) is a dead giveaway, that there's a break (or return) inside the loop. When not abused, it can make for a very clear yet concise loop construct. –  hyde Commented Mar 20, 2014 at 16:12

That sort of construction shows up when doing some sort of buffered read, where the read fills a buffer and returns the number of bytes read, or 0. It's a pretty familiar construct.

There's a risk someone might think you got = confused with == . You might get a warning if you're using a style checker.

Honestly, I'd be more bothered by the (...).size() than the assignment. That seems a little iffy, because you're dereferencing the assignment. ;)

I don't think there's a hard rule, unless you're strictly following the advice of a style checker & it flags it with a warning.

sea-rob's user avatar

Duplication is like medicine. It's harmful in high doses, but can be beneficial when appropriately used in low doses. This situation is one of the helpful cases, as you've already refactored out the worst duplication into the getCurrentStrings() function. I agree with Sebastian, though, that it's better written as a for loop.

Along those same lines, if this pattern is coming up all the time, it might be a sign that you need to create better abstractions, or rearrange responsibilities between different classes or functions. What makes loops like these problematic is they rely heavily on side effects. In certain domains that's not always avoidable, like I/O for example, but you should still try to push side effect-dependent functions as deep into your abstraction layers as possible, so there aren't very many of them.

In your example code, without knowing the context, the first thing I would do is try to find a way to refactor it to do all the work on my local copy of currentStrings , then update the external state all at once. Something like:

If the current strings are being updated by another thread, an event model is often in order:

You get the picture. There's usually some way to refactor your code to not depend on side effects as much. If that's not practical, you can often avoid duplication by moving some responsibility to another class, as in:

It might seem like overkill to create a whole new CurrentStrings class for something that can be mostly served by a List<String> , but it will often open up a whole gamut of simplifications throughout your code. Not to mention the encapsulation and type-checking benefits.

Karl Bielefeldt's user avatar

  • 3 Why would you ever write something as a for loop when you don't know ahead of time how many iterations you're going to have? That's what while is for. –  Robert Harvey Commented Mar 20, 2014 at 16:01
  • 1 That's a whole question in itself, but for loops have a defined initial condition, stop condition, update, and body. Usually when those four elements exist and are not overly complex, it's preferable to use a for loop. For one thing, it limits the scope of loop variables to the loop body itself. For another, it provides an unambiguous place to look for those elements, which is a big readability boost in a large loop. Loops with fixed iteration counts happen to fit the for loop criteria, but that doesn't mean they're the only kind of loops that do. –  Karl Bielefeldt Commented Mar 20, 2014 at 16:30
  • Well, if I were using a loop variable (that increments or decrements in each loop iteration), I wouldn't use a while anyway. That's not the case in the OP. –  Robert Harvey Commented Mar 20, 2014 at 16:32
  • Sure it is. currentStrings is a loop variable. It changes on every iteration and is the basis for the stop condition. It doesn't have to be a counter. –  Karl Bielefeldt Commented Mar 20, 2014 at 16:36
  • Yeah, thought I qualified my use of the term "loop variable" in my last comment. Oh, well. –  Robert Harvey Commented Mar 20, 2014 at 16:37

The former code seems more rational and readable to me and the whole loop also makes perfect sense. I'm not sure about the context of the program, but there is nothing wrong with the loop structure in essence.

The later example seems trying to write a Clever code, that is absolutely confusing to me in the first glance.

I also agree with Rob Y 's answer that in the very first glance you might think it should be an equation == rather than an assignment , however if you actually read the while statement to the end you will realize it's not a typo or mistake, however the problem is that you can't clearly understand Why there is an assignment within the while statement unless you keep the function name exactly same as doThingsThatCanAlterCurrentStrings or add an inline comment that explains the following function is likely to change the value of currentStrings .

Mahdi's user avatar

Your Answer

Reminder: Answers generated by artificial intelligence tools are not allowed on Software Engineering Stack Exchange. Learn more

Sign up or log in

Post as a guest.

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy .

Not the answer you're looking for? Browse other questions tagged code-smell conditions loops or ask your own question .

  • The Overflow Blog
  • The hidden cost of speed
  • The creator of Jenkins discusses CI/CD and balancing business with open source
  • Featured on Meta
  • Announcing a change to the data-dump process
  • Bringing clarity to status tag usage on meta sites

Hot Network Questions

  • What`s this? (Found among circulating tumor cells)
  • In a tabular with p-column, line spacing after multi-line cell too short with the array package
  • A seven letter *
  • Intersection of Frobenius subalgebra objects
  • DateTime.ParseExact returns today if date string and format are set to "General"
  • Numbers, or are they?
  • An instructor is being added to co-teach a course for questionable reasons, against the course author's wishes—what can be done?
  • Gravitational potential energy of a water column
  • What is the optimal number of function evaluations?
  • Is the 2024 Ukrainian invasion of the Kursk region the first time since WW2 Russia was invaded?
  • PCA to help select variables?
  • \ExplSyntaxOn problem with new paragraph
  • Replacing jockey wheels on Shimano Deore rear derailleur
  • Is it helpful to use a thicker gauge wire for only part of a long circuit run that could have higher loads?
  • I'm not quite sure I understand this daily puzzle on Lichess (9/6/24)
  • How to clean a female disconnect connector
  • Children in a field trapped under a transparent dome who interact with a strange machine inside their car
  • Is there a non-semistable simple sheaf?
  • Are there alternative methods, beyond Bayesian or probabilistic approaches, for modeling the relationship between evidence and hypothesis credibility?
  • In which town of Europe (Germany ?) were this 2 photos taken during WWII?
  • Why does Jeff think that having a story at all seems gross?
  • Where is this railroad track as seen in Rocky II during the training montage?
  • What prevents random software installation popups from mis-interpreting our consents
  • What was the typical amount of disk storage for a mainframe installation in the 1980s?

assignment within if statement c

  • Trending Now
  • Foundational Courses
  • Data Science
  • Practice Problem
  • Machine Learning
  • System Design
  • DevOps Tutorial

Nested If Else Statement in Programming

Nested If Else Statements are a fundamental concept in programming. They allow us to create more complex decision-making structures by placing one if else statement inside another. In this article, we will discuss the Nested if else statement.

Table of Content

What is Nested If Else Statement?

  • Syntax of Nested If Else Statement
  • Nested If Else Statement in C
  • Nested If Else Statement in C++
  • Nested If Else Statement in Java
  • Nested If Else Statement in Python
  • Nested If Else Statement in C#
  • Nested If Else Statement in JavaScript
  • Best Practices of Nested If Else Statement
  • Use Cases of Nested If Else Statement

Nested if else statements allow for more complex decision-making within the program. You can nest if else statements with other if else statements, creating conditions at multiple levels.

Syntax of Nested If Else Statement:

Nested if else statement in c:.

Here are the implementation of Nested if else statement in C language:

Nested If Else Statement in C++:

Here are the implementation of Nested if else statement in C++ language:

Nested If Else Statement in Java:

Here are the implementation of Nested if else statement in java language:

Nested If Else Statement in Python:

Here are the implementation of Nested if else statement in python language:

Nested If Else Statement in C#:

Here are the implementation of Nested if else statement in C# language:

Nested If Else Statement in JavaScript:

Here are the implementation of Nested if else statement in javascript language:

Best Practices of Nested If Else Statement:

  • Keep it Simple : Don’t make your if else chains too long or complicated.
  • Use Clear Conditions : Use descriptive conditions so anyone reading your code can understand what’s happening.
  • Avoid Redundancy : Don’t repeat the same conditions unnecessarily.
  • Exit Early : Use return or break to exit the if else chain as soon as possible.
  • Consider Alternatives : Sometimes, using ternary operators or switch-case statements can make your code clearer.
  • Add Comments : If your logic is complex, explain it with comments so others (and your future self) can understand.

Use Cases of Nested If Else Statement:

  • Grading System : If a student’s score is greater than or equal to 90, they get an ‘A’. If not, check if it’s greater than or equal to 80 for a ‘B’, and so on.
  • Shopping Cart Discounts : If the user is a premium member, apply a 10% discount. If not, check if the total exceeds a certain amount for a 5% discount.
  • Authentication and Authorization : If the user’s credentials are valid, check their role. Depending on the role, grant access to different parts of the system.
  • Weather Forecast : If the temperature is above 30°C, it’s hot. If not, check if it’s between 20-30°C for a moderate forecast, and so on.
  • Game Development : If the player’s health is less than or equal to 0, they lose the game. If not, check if they have enough ammo to continue fighting.

Conclusion:

Use nested if else statements in programming when you need to evaluate conditions within other conditions. It helps you handle complex scenarios by branching your code based on various possibilities.

Please Login to comment...

Similar reads.

  • Programming
  • Discord Emojis List 2024: Copy and Paste
  • Best Adblockers for Twitch TV: Enjoy Ad-Free Streaming in 2024
  • PS4 vs. PS5: Which PlayStation Should You Buy in 2024?
  • Best Mobile Game Controllers in 2024: Top Picks for iPhone and Android
  • System Design Netflix | A Complete Architecture

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

cppreference.com

Assignment operators.

(C++20)
(C++20)
(C++11)
(C++20)
(C++17)
(C++11)
(C++11)
General topics
(C++11)
-
-expression
block


/
(C++11)
(C++11)
(C++11)
(C++20)
(C++20)
(C++11)

expression
pointer
specifier

specifier (C++11)
specifier (C++11)
(C++11)

(C++11)
(C++11)
(C++11)
General
(C++11)
(C++20)
(C++26)
(C++11)
(C++11)
-expression
-expression
-expression
(C++11)
(C++11)
(C++17)
(C++20)
    

Assignment operators modify the value of the object.

Operator name  Syntax  Prototype examples (for class T)
Inside class definition Outside class definition
simple assignment Yes T& T::operator =(const T2& b);
addition assignment Yes T& T::operator +=(const T2& b); T& operator +=(T& a, const T2& b);
subtraction assignment Yes T& T::operator -=(const T2& b); T& operator -=(T& a, const T2& b);
multiplication assignment Yes T& T::operator *=(const T2& b); T& operator *=(T& a, const T2& b);
division assignment Yes T& T::operator /=(const T2& b); T& operator /=(T& a, const T2& b);
remainder assignment Yes T& T::operator %=(const T2& b); T& operator %=(T& a, const T2& b);
bitwise AND assignment Yes T& T::operator &=(const T2& b); T& operator &=(T& a, const T2& b);
bitwise OR assignment Yes T& T::operator |=(const T2& b); T& operator |=(T& a, const T2& b);
bitwise XOR assignment Yes T& T::operator ^=(const T2& b); T& operator ^=(T& a, const T2& b);
bitwise left shift assignment Yes T& T::operator <<=(const T2& b); T& operator <<=(T& a, const T2& b);
bitwise right shift assignment Yes T& T::operator >>=(const T2& b); T& operator >>=(T& a, const T2& b);

this, and most also return *this so that the user-defined operators can be used in the same manner as the built-ins. However, in a user-defined operator overload, any type can be used as return type (including void). can be any type including .
Definitions Assignment operator syntax Built-in simple assignment operator Assignment from an expression Assignment from a non-expression initializer clause Built-in compound assignment operator Example Defect reports See also

[ edit ] Definitions

Copy assignment replaces the contents of the object a with a copy of the contents of b ( b is not modified). For class types, this is performed in a special member function, described in copy assignment operator .

replaces the contents of the object a with the contents of b, avoiding copying if possible (b may be modified). For class types, this is performed in a special member function, described in .

(since C++11)

For non-class types, copy and move assignment are indistinguishable and are referred to as direct assignment .

Compound assignment replace the contents of the object a with the result of a binary operation between the previous value of a and the value of b .

[ edit ] Assignment operator syntax

The assignment expressions have the form

target-expr new-value (1)
target-expr op new-value (2)
target-expr - the expression to be assigned to
op - one of *=, /= %=, += -=, <<=, >>=, &=, ^=, |=
new-value - the expression (until C++11) (since C++11) to assign to the target
  • ↑ target-expr must have higher precedence than an assignment expression.
  • ↑ new-value cannot be a comma expression, because its precedence is lower.

If new-value is not an expression, the assignment expression will never match an overloaded compound assignment operator.

(since C++11)

[ edit ] Built-in simple assignment operator

For the built-in simple assignment, the object referred to by target-expr is modified by replacing its value with the result of new-value . target-expr must be a modifiable lvalue.

The result of a built-in simple assignment is an lvalue of the type of target-expr , referring to target-expr . If target-expr is a bit-field , the result is also a bit-field.

[ edit ] Assignment from an expression

If new-value is an expression, it is implicitly converted to the cv-unqualified type of target-expr . When target-expr is a bit-field that cannot represent the value of the expression, the resulting value of the bit-field is implementation-defined.

If target-expr and new-value identify overlapping objects, the behavior is undefined (unless the overlap is exact and the type is the same).

If the type of target-expr is volatile-qualified, the assignment is deprecated, unless the (possibly parenthesized) assignment expression is a or an .

(since C++20)

new-value is only allowed not to be an expression in following situations:

is of a , and new-value is empty or has only one element. In this case, given an invented variable t declared and initialized as T t = new-value , the meaning of x = new-value  is x = t. is of class type. In this case, new-value is passed as the argument to the assignment operator function selected by .   <double> z; z = {1, 2}; // meaning z.operator=({1, 2}) z += {1, 2}; // meaning z.operator+=({1, 2})   int a, b; a = b = {1}; // meaning a = b = 1; a = {1} = b; // syntax error
(since C++11)

In overload resolution against user-defined operators , for every type T , the following function signatures participate in overload resolution:

& operator=(T*&, T*);
volatile & operator=(T*volatile &, T*);

For every enumeration or pointer to member type T , optionally volatile-qualified, the following function signature participates in overload resolution:

operator=(T&, T);

For every pair A1 and A2 , where A1 is an arithmetic type (optionally volatile-qualified) and A2 is a promoted arithmetic type, the following function signature participates in overload resolution:

operator=(A1&, A2);

[ edit ] Built-in compound assignment operator

The behavior of every built-in compound-assignment expression target-expr   op   =   new-value is exactly the same as the behavior of the expression target-expr   =   target-expr   op   new-value , except that target-expr is evaluated only once.

The requirements on target-expr and new-value of built-in simple assignment operators also apply. Furthermore:

  • For + = and - = , the type of target-expr must be an arithmetic type or a pointer to a (possibly cv-qualified) completely-defined object type .
  • For all other compound assignment operators, the type of target-expr must be an arithmetic type.

In overload resolution against user-defined operators , for every pair A1 and A2 , where A1 is an arithmetic type (optionally volatile-qualified) and A2 is a promoted arithmetic type, the following function signatures participate in overload resolution:

operator*=(A1&, A2);
operator/=(A1&, A2);
operator+=(A1&, A2);
operator-=(A1&, A2);

For every pair I1 and I2 , where I1 is an integral type (optionally volatile-qualified) and I2 is a promoted integral type, the following function signatures participate in overload resolution:

operator%=(I1&, I2);
operator<<=(I1&, I2);
operator>>=(I1&, I2);
operator&=(I1&, I2);
operator^=(I1&, I2);
operator|=(I1&, I2);

For every optionally cv-qualified object type T , the following function signatures participate in overload resolution:

& operator+=(T*&, );
& operator-=(T*&, );
volatile & operator+=(T*volatile &, );
volatile & operator-=(T*volatile &, );

[ edit ] Example

Possible output:

[ edit ] Defect reports

The following behavior-changing defect reports were applied retroactively to previously published C++ standards.

DR Applied to Behavior as published Correct behavior
C++11 for assignments to class type objects, the right operand
could be an initializer list only when the assignment
is defined by a user-defined assignment operator
removed user-defined
assignment constraint
C++11 E1 = {E2} was equivalent to E1 = T(E2)
( is the type of ), this introduced a C-style cast
it is equivalent
to E1 = T{E2}
C++20 compound assignment operators for volatile
-qualified types were inconsistently deprecated
none of them
is deprecated
C++11 an assignment from a non-expression initializer clause
to a scalar value would perform direct-list-initialization
performs copy-list-
initialization instead
C++20 bitwise compound assignment operators for volatile types
were deprecated while being useful for some platforms
they are not
deprecated

[ edit ] See also

Operator precedence

Operator overloading

Common operators

a = b
a += b
a -= b
a *= b
a /= b
a %= b
a &= b
a |= b
a ^= b
a <<= b
a >>= b

++a
--a
a++
a--

+a
-a
a + b
a - b
a * b
a / b
a % b
~a
a & b
a | b
a ^ b
a << b
a >> b

!a
a && b
a || b

a == b
a != b
a < b
a > b
a <= b
a >= b
a <=> b

a[...]
*a
&a
a->b
a.b
a->*b
a.*b

function call
a(...)
comma
a, b
conditional
a ? b : c
Special operators

converts one type to another related type
converts within inheritance hierarchies
adds or removes -qualifiers
converts type to unrelated type
converts one type to another by a mix of , , and
creates objects with dynamic storage duration
destructs objects previously created by the new expression and releases obtained memory area
queries the size of a type
queries the size of a (since C++11)
queries the type information of a type
checks if an expression can throw an exception (since C++11)
queries alignment requirements of a type (since C++11)

for Assignment operators
  • Recent changes
  • Offline version
  • What links here
  • Related changes
  • Upload file
  • Special pages
  • Printable version
  • Permanent link
  • Page information
  • In other languages
  • This page was last modified on 25 January 2024, at 23:41.
  • Privacy policy
  • About cppreference.com
  • Disclaimers

Powered by MediaWiki

  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand
  • OverflowAI GenAI features for Teams
  • OverflowAPI Train & fine-tune LLMs
  • Labs The future of collective knowledge sharing
  • About the company Visit the blog

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Get early access and see previews of new features.

Variable assignment inside a C++ 'if' statement

In C++, the following is valid and I can run it without a problem:

However, even though the following should also be valid, it gives me an error:

Furthermore, in C++17 the below code must be valid too, but it gives me a similar error again:

I am trying to compile with g++ test.cpp -std=c++17 . g++ --version gives me g++ (Ubuntu 5.4.0-6ubuntu1~16.04.12) 5.4.0 20160609 . What am I missing here?

  • if-statement
  • variable-assignment

Peter Mortensen's user avatar

  • @FoggyDay Yes you can declare a variable in an if condition. Try it. if(int i=5) works. –  walnut Commented Mar 16, 2020 at 4:27
  • No matter if it is accepted by the compiler or not, what is the intent? What is the if statement supposed to test? Is the intent to limit the scope of variable i ? Is that case, a naked " {} " block can be used. It doesn't require an if statement. Or is the intent something else? Can you make the intent clear in the question? (But without "Edit:", "Update:", or similar - the question/answer should appear as if it was written today.) –  Peter Mortensen Commented Jun 26, 2022 at 16:53
  • Here is a question with a similar structure, but without the (close by) declaration: Put a condition check and variable assignment in one 'if' statement –  Peter Mortensen Commented Jun 26, 2022 at 17:48
  • Was the intent to limit the scope of variable i ? –  Peter Mortensen Commented Jun 28, 2022 at 21:56

2 Answers 2

if ((int i=5) == 5) is a syntax error. It does not match any supported syntax for if statements. The syntax is init-statement(optional) condition , where condition could either be an expression, or a declaration with initializer. You can read more detail about the syntax on cppreference .

if (int i=5; i == 5) is correct. However, you are using an old version of GCC that dates from before C++17 was standardized. You would need to upgrade your compiler version. According to C++ Standards Support in GCC this feature was added in GCC 7.

M.M's user avatar

  • Yes I was wrong to do if ((int i=5) == 5) . Upgrading g++ to version 9 solved the second problem. –  doca Commented Mar 16, 2020 at 4:46

For starters, I believe your compiler is right to reject

because this is not legal C++ code. A variable declaration statement isn’t an expression, so you can’t treat (int i = 5) as an expression.

For the second one, I suspect you just need to update your compiler. g++ 5.6 is a fairly old version at this point, and I believe more updates versions of g++ will handle that code with no problem.

templatetypedef's user avatar

Your Answer

Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more

Sign up or log in

Post as a guest.

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy .

Not the answer you're looking for? Browse other questions tagged c++ c++11 if-statement c++17 variable-assignment or ask your own question .

  • The Overflow Blog
  • The hidden cost of speed
  • The creator of Jenkins discusses CI/CD and balancing business with open source
  • Featured on Meta
  • Announcing a change to the data-dump process
  • Bringing clarity to status tag usage on meta sites
  • What does a new user need in a homepage experience on Stack Overflow?
  • Feedback requested: How do you use tag hover descriptions for curating and do...
  • Staging Ground Reviewer Motivation

Hot Network Questions

  • Topos notions coming from topology and uniqueness of generalizations
  • What was the typical amount of disk storage for a mainframe installation in the 1980s?
  • The question about the existence of an infinite non-trivial controversy
  • Confusion about time dilation
  • A seven letter *
  • What does "dare not" mean in a literary context?
  • In which town of Europe (Germany ?) were this 2 photos taken during WWII?
  • Why is this bolt's thread the way it is?
  • Are there alternative methods, beyond Bayesian or probabilistic approaches, for modeling the relationship between evidence and hypothesis credibility?
  • Is there a way to prove ownership of church land?
  • Websites assume the wrong country after using a VPN
  • Cardinality of connected LOTS
  • Representing permutation groups as equivalence relations
  • Questions about LWE in NIST standards
  • Where is this railroad track as seen in Rocky II during the training montage?
  • What was Jesus' issue with Mary touching him after he'd returned to earth after His resurrection?
  • help to grep a string from a site
  • How should I tell my manager that he could delay my retirement with a raise?
  • Is there a way to read lawyers arguments in various trials?
  • Children in a field trapped under a transparent dome who interact with a strange machine inside their car
  • I'm not quite sure I understand this daily puzzle on Lichess (9/6/24)
  • Visual assessment of scatterplots acceptable?
  • How high does the ocean tide rise every 90 minutes due to the gravitational pull of the space station?
  • How can I play MechWarrior 2?

assignment within if statement c

COMMENTS

  1. C assignments in an 'if' statement

    Connect and share knowledge within a single location that is structured and easy to search. ... Yes, an assignment...well assigns...but it's also an expression. Any value not equalling zero will be evaluated as true and zero as false. ... Your code is assigning data[q] to s and then returns s to the if statement.

  2. Decision Making in C (if , if..else, Nested if, if-else-if )

    4. if-else-if Ladder in C. The if else if statements are used when the user has to decide among multiple options. The C if statements are executed from the top down. As soon as one of the conditions controlling the if is true, the statement associated with that if is executed, and the rest of the C else-if ladder is bypassed.

  3. C

    C - if Statement

  4. If...Else Statement in C Explained

    Conditional code flow is the ability to change the way a piece of code behaves based on certain conditions. In such situations you can use if statements.. The if statement is also known as a decision making statement, as it makes a decision on the basis of a given condition or expression. The block of code inside the if statement is executed is the condition evaluates to true.

  5. C if...else Statement

    C if...else Statement

  6. C

    C - Nested If Statements. It is always legal in C programming to nest if-else statements, which means you can use one if or else-if statement inside another if or else-if statement (s). In the programming context, the term "nesting" refers to enclosing a particular programming element inside another similar element.

  7. If Statement in C

    If Statement in C - How to use If-Else ...

  8. C Conditional Statement: IF, IF Else and Nested IF Else with ...

    This process is called decision making in 'C.'. In 'C' programming conditional statements are possible with the help of the following two constructs: 1. If statement. 2. If-else statement. It is also called as branching as a program decides which statement to execute based on the result of the evaluated condition.

  9. Nested IF ELSE Statement in C

    Here is our nested if-else statement, which checks to see if n is divisible by 8. If condition 2 returns true, we proceed to execute line 1. We print here that the integer is even and divisible by 8. If condition 2 is false, we enter the else statement and print that the number is even but not divisible by 8. Similarly, if condition 1 evaluates ...

  10. Conditional Statements in C: if, if..else, Nested if

    else. printf("%d is not greater than %d\n",a,b); return 0; In the above code in the C Online Compiler, the first if statement checks whether a>b. If a is greater than b, the nested if statement is checked. If the nested if condition is false, the else statement in the nested if block gets executed.

  11. if-else statements in C

    Statements under the else block are executed only when the if condition is false. Syntax: As usual, if you have only one statement in the else block then the braces ({}) can be omitted. Although, it is not recommended. As already said, indentation is not required, so the above code can also be written as:

  12. C if...else Statement

    C if...else Statement

  13. creating conditions and branches in C with if/else statements

    printf("The number is negative\n"); In this example, we add additional branch with if else. We generate random values between -5 and 4. With the help of the if & else statement we print a message for all three options. We run the example a few times. In this article, we have covered if else conditions in C.

  14. Is doing an assignment inside a condition considered a code smell?

    C++ culture is more accepting of assignment-in-condition than the other languages, and implicit boolean conversions are actually used in some idioms, e.g. type queries: ... however the problem is that you can't clearly understand Why there is an assignment within the while statement unless you keep the function name exactly same as ...

  15. Nested If Else Statement in Programming

    Nested If Else Statement in Programming

  16. c++

    The result of the assignment operation is the value stored in the left operand after the assignment has taken place; the result is an lvalue. The result of the expression a = 5 is 5. [6.4/4] [..] The value of a condition that is an expression is the value of the expression, implicitly converted to bool for statements other than switch.

  17. if statement

    Copy assignment: Move assignment (C++11) Destructor: Templates: Class template: Function template: Template specialization: ... Conditionally executes another statement. ... detects whether the call occurs within a constant-evaluated context (function) C documentation for if statement.

  18. Assignment operators

    Assignment operators

  19. Variable assignment inside a C++ 'if' statement

    A variable declaration statement isn't an expression, so you can't treat (int i = 5) as an expression. For the second one, I suspect you just need to update your compiler. g++ 5.6 is a fairly old version at this point, and I believe more updates versions of g++ will handle that code with no problem.