• 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.

When would you want to assign a variable in an if condition? [duplicate]

I recently just lost some time figuring out a bug in my code which was caused by a typo:

instead of:

I was wondering if there is any particular case you would want to assign a value to a variable in a if statement, or if not, why doesn't the compiler throw a warning or an error?

  • if-statement

Jan Schultke's user avatar

  • 4 I depends, my compiler throws a warning when a = b –  user1944441 Commented Jul 16, 2013 at 16:03
  • 3 The compiler doesn't issue a diagnostic because it is not mandated to do so. It is perfectly valid C++ code. –  Alok Save Commented Jul 16, 2013 at 16:05
  • 7 Most compilers will warn about this, as long as you enable the warning. –  Mike Seymour Commented Jul 16, 2013 at 16:07
  • 3 I vote against treating this as a duplicate of stackoverflow.com/q/151850/2932052 , because this is an actual C/C++ question that arises often whereas the other is very vague and language-agnostic. Maybe it's really only a C/C++ problem? In this case the other should get the tag and this question should be treated as duplicate. –  Wolf Commented Apr 23, 2019 at 9:27
  • 2 Does this answer your question? Inadvertent use of = instead of == –  outis Commented Jun 30, 2022 at 5:42

9 Answers 9

Though this is oft cited as an anti-pattern ("use virtual dispatch!"), sometimes the Derived type has functionality that the Base simply does not (and, consequently, distinct functions), and this is a good way to switch on that semantic difference.

Lightness Races in Orbit's user avatar

  • 17 The anti-pattern is putting a definition in the condition. It's a sure recipe for unreadable and unmaintainable code. –  James Kanze Commented Jul 16, 2013 at 16:25
  • 76 Putting the definition in the condition tightens the scope so that you don't accidentally refer to derived on the next line after the if-statement. It's the same reason we use for (int i = 0... instead of int i; for (i = 0; ... . –  Adrian McCarthy Commented Jul 16, 2013 at 16:36
  • 62 @JamesKanze - Others find it increases readability and maintainability, partly by minimizing the scope of the variable. "To avoid accidental misuse of a variable, it is usually a good idea to introduce the variable into the smallest scope possible. In particular, it is usually best to delay the definition of a variable until one can give it an initial value ... One of the most elegant applications of these two principles is to declare a variable in a conditional." -- Stroustrup, "The C++ Programming Language." –  Andy Thomas Commented Jul 16, 2013 at 16:40
  • 13 @James: Nobody in my team has had a problem either reading or maintaining the code, in the ten years our codebase has taken this approach. –  Lightness Races in Orbit Commented Jul 16, 2013 at 17:42
  • 15 Funny thing about the scope of the variable when putting a definition in the condition is that the variable is also accessible in the else -clause as well. if (T t = foo()) { dosomething(t); } else { dosomethingelse(t); } –  dalle Commented Jul 18, 2013 at 8:57

Here is some history on the syntax in question.

In classical C, error handling was frequently done by writing something like:

Or, whenever there was a function call that might return a null pointer, the idiom was used the other way round:

However, this syntax is dangerously close to

which is why many people consider the assignment inside a condition bad style, and compilers started to warn about it (at least with -Wall ). Some compilers allow avoiding this warning by adding an extra set of parentheses:

However, this is ugly and somewhat of a hack, so it's better avoid writing such code.

Then C99 came around, allowing you to mix definitions and statements, so many developers would frequently write something like

which does feel awkward. This is why the newest standard allows definitions inside conditions, to provide a short, elegant way to do this:

There isn't any danger in this statement anymore. You explicitly give the variable a type, obviously wanting it to be initialized. It also avoids the extra line to define the variable, which is nice. But most importantly, the compiler can now easily catch this sort of bug:

Without the variable definition inside the if statement, this condition would not be detectable.

To make a long answer short: The syntax in you question is the product of old C's simplicity and power, but it is evil, so compilers can warn about it. Since it is also a very useful way to express a common problem, there is now a very concise, bug robust way to achieve the same behavior. And there are a lot of good, possible uses for it.

Peter Mortensen's user avatar

  • 1 But adding extra parenthesis is not "bug robust": approxion.com/a-gcc-compiler-mistake The MISRA-compliant code if ((a == b) && (c = d)) won't generate a warning or error because of GCC's "feature". Instead of "bug robust" it's perniciously buggy , You think using -Wall -Werror protects you from such bugs, but it actually doesn't . –  Andrew Henle Commented Jun 6, 2021 at 12:12
  • 2 @AndrewHenle Well, that part about assignment in extra brackets was only to illustrate what has been done many times in real existing code. Of course , the extra parentheses are only a hack. Of course , they look ugly. Of course , this is just an extra reason to prefer the C++ variable declaration over a C assignment in an if() statement. You may question the sensibility of GCC's warning behavior, but that has no impact on my answer at all. –  cmaster - reinstate monica Commented Jun 6, 2021 at 13:16
  • 1 The issue isn't with your answer - I think it's about the best possible factual discussion of the history of the "assignment in an if-statement" style came about. The problem is your answer was referred by someone who utterly missed your characterization of GCC's hack and actually used your answer as a defense of that hack. I was pointing out how GCC's hack actually opens the door to even more subtle bugs when more complex code is involved. That evil aspect of the GCC "extra parentheses" hack seems to be utterly missed by proponents of cramming assignments into if statements. –  Andrew Henle Commented Jun 6, 2021 at 16:12
  • 3 @AndrewHenle Thanks for the explanation. It gets me thinking that it might be beneficial to point out that this is a hack, and that I discourage using it. –  cmaster - reinstate monica Commented Jun 6, 2021 at 18:44

The assignment operator returns the value of the assigned value . So, I might use it in a situation like this:

I assign x to be the value returned by getMyNumber and I check if it's not zero.

Avoid doing that. I gave you an example just to help you understand this.

To avoid such bugs up to some extent, one should write the if condition as if(NULL == ptr) instead of if (ptr == NULL) . Because when you misspell the equality check operator == as operator = , the compiler will throw an lvalue error with if (NULL = ptr) , but if (res = NULL) passed by the compiler (which is not what you mean) and remain a bug in code for runtime.

One should also read Criticism regarding this kind of code.

Maroun's user avatar

  • 14 I want to learn/improve myself, please mention why you downvote. –  Maroun Commented Jul 16, 2013 at 16:16
  • 2 I frequently use if(fp = fopen("file", "w")){ // file not open} else{ // file processing } –  Grijesh Chauhan Commented Jul 16, 2013 at 19:00
  • 18 Reversing the operands of an equality comparison, such as writing (NULL == ptr) rather than (ptr == NULL) , is controversial. Personally, I hate it; I find it jarring, and I have to mentally re-reverse it to understand it. (Others obviously don't have that issue). The practice is referred to as "Yoda conditions" . Most compilers can be persuaded to warn about assignments in conditions anyway. –  Keith Thompson Commented Jul 16, 2013 at 19:30
  • 1 I think its nice to know the trick! I added as an information, Some people may like it. That is why its just a suggestion. –  Grijesh Chauhan Commented Jul 16, 2013 at 20:01
  • 1 @LilianA.Moraru For some it is helpful. That's why it's a suggestion, if you don't like it you don't have to use it. –  Maroun Commented Oct 17, 2017 at 8:36
why doesn't the compiler throw a warning

Some compilers will generate warnings for suspicious assignments in a conditional expression, though you usually have to enable the warning explicitly.

For example, in Visual C++ , you have to enable C4706 (or level 4 warnings in general). I generally turn on as many warnings as I can and make the code more explicit in order to avoid false positives. For example, if I really wanted to do this:

Then I'd write it as:

The compiler sees the explicit test and assumes that the assignment was intentional, so you don't get a false positive warning here.

The only drawback with this approach is that you can't use it when the variable is declared in the condition. That is, you cannot rewrite:

Syntactically, that doesn't work. So you either have to disable the warning, or compromise on how tightly you scope x .

C++17 added the ability to have an init-statement in the condition for an if statement ( p0305r1 ), which solves this problem nicely (for kind of comparison, not just != 0 ).

Furthermore, if you want, you can limit the scope of x to just the if statement:

Adrian McCarthy's user avatar

  • The explicit comparison if((x = Foo()) != 0) is unnecessary: adding an extra pair of parentheses if((x = Foo())) will silence the warning just as well. Also, there is a big difference between if(x = Foo()) and if(int x = Foo()) , the later clearly states that you want to do an initialization, not a comparison, so no compiler in their right mind would want to throw a warning on this. –  cmaster - reinstate monica Commented Aug 26, 2013 at 17:35
  • 2 To be fair, you don't have to compromise how tightly you scope x if you are willing to surround your block with extra braces. But I wager this is not usually worth it. –  Thomas Eding Commented Aug 26, 2013 at 18:30
  • 2 @cmaster: Explicit comparison is necessary if you want to check something other than != 0 . Explicit comparison is also clearer than an extra set of parentheses. –  Adrian McCarthy Commented Aug 26, 2013 at 20:33
  • 1 @AdrianMcCarthy: Explicit comparison also requires that extra set of parentheses (due to operator precedence). So the addition of ` != 0` is always just extra code. Of course, you are right that explicit comparison can compare to anything. If you are comparing against 0, however, I heartily disagree with you: This is such a common idiom that I expect the shorter version in that case, so that the extra ` != 0` has the effect of a small pothole to me... –  cmaster - reinstate monica Commented Aug 26, 2013 at 20:53
  • 1 @cmaster: That may be the case for you. But other programmers may be confused and think the extra parentheses are superfluous. They could delete them (which might not bother the compiler if they haven't enabled the same warning). Then someone will come along and think the assignment was supposed to be == , and now you've got two bugs. The explicit comparison makes it obvious clear why the extra parentheses are there and, more importantly, that the assignment was not a typo. –  Adrian McCarthy Commented Mar 27, 2019 at 12:11

In C++17 , one can use:

Similar to a for loop iterator initializer.

Here is an example:

DevBro's user avatar

It depends on whether you want to write clean code or not. When C was first being developed, the importance of clean code wasn't fully recognized, and compilers were very simplistic: using nested assignment like this could often result in faster code. Today, I can't think of any case where a good programmer would do it. It just makes the code less readable and more difficult to maintain.

James Kanze's user avatar

  • 1 I agree that it's less readable but only if the assignment is the only thing in the if statement. If it's something like if ((x = function()) > 0) then I think that's perfectly fine. –  ashishduh Commented Mar 24, 2014 at 19:29
  • 2 @user1199931 Not really. If you're scanning the code to get a general understanding of it, you'll see the if and continue, and miss the fact that there is a change of state. There are exceptions ( for , but the keyword itself says that it is both looping and managing the loop state), but in general, a line of code should do one, and only one thing. If it controls flow, it shouldn't modify state. –  James Kanze Commented Mar 26, 2014 at 13:41
  • 3 "Clean code" is a very subjective term, unfortunately. –  Michael Warner Commented Jan 11, 2016 at 22:01

Suppose you want to check several conditions in a single if , and if any one of the conditions is true, you'd like to generate an error message. If you want to include in your error message which specific condition caused the error, you could do the following:

So if the second condition is the one that evaluates to true, e will be equal to "cd". This is due to the short-circuit behaviour of || which is mandated by the standard (unless overloaded). See this answer for more details on short-circuiting.

elatalhm's user avatar

  • Interesting, but isn't it also for showing cleverness? –  Wolf Commented Apr 23, 2019 at 9:50
  • Using const char* e; instead of std::string e; would make it faster, but the similarity of the lines seems to ask for a loop over {"ab", "cd", "ef"}; . –  Wolf Commented Oct 1, 2021 at 10:15

Doing assignment in an if is a fairly common thing, though it's also common that people do it by accident.

The usual pattern is:

The anti-pattern is where you're mistakenly assigning to things:

You can avoid this to a degree by putting your constants or const values first, so your compiler will throw an error:

= vs. == is something you'll need to develop an eye for. I usually put whitespace around the operator so it's more obvious which operation is being performed, as longname=longername looks a lot like longname==longername at a glance, but = and == on their own are obviously different.

tadman's user avatar

  • 10 They're both anti patterns. And as for if ( 1 == x ) , it's not the natural way of expressing the test, and any compiler worth its salt will warn for if ( x = 1 ) , so there's really no reason for being ugly here either. –  James Kanze Commented Jul 16, 2013 at 16:10
  • 1 The 1 == x pattern, anti or not, comes from Code Complete so you'll see it fairly often. It's a bit ugly, but might be a reasonable requirement for people that have a problem getting this right, serving as training wheels. –  tadman Commented Jul 16, 2013 at 16:17
  • 3 @tadman The way to teach people is by annoying them with warnings about this typo, not to switch to yoda conditions. –  stefan Commented Jul 16, 2013 at 16:18
  • 2 @stefan Especially as most compilers have an option to turn warnings into errors. –  James Kanze Commented Jul 16, 2013 at 16:21
  • @tadman: And reasonable compiler warnings catch more instances of this mistake than Yoda conditions do. And Yoda conditions only help when you remember to use them. –  Adrian McCarthy Commented Jul 16, 2013 at 16:22

a quite common case. use

this kind of typo will cause compile error

Kevin Chan's user avatar

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

  • The Overflow Blog
  • The evolution of full stack engineers
  • One of the best ways to get value for AI coding tools: generating tests
  • Featured on Meta
  • User activation: Learnings and opportunities
  • Site maintenance - Mon, Sept 16 2024, 21:00 UTC to Tue, Sept 17 2024, 2:00...
  • Staging Ground Reviewer Motivation
  • What does a new user need in a homepage experience on Stack Overflow?

Hot Network Questions

  • Movie where a young director's student film gets made (badly) by a major studio
  • Taylor Swift - Use of "them" in her text "she fights for the rights and causes I believe need a warrior to champion them"
  • grouping for stdout
  • BASH - Find file with regex - Non-recursively delete number-only filenames in directory
  • Does the word vaishnava appear even once in Srimad Bhagavatam?
  • What came of the Trump campaign's complaint to the FEC that Harris 'stole' (or at least illegally received) Biden's funding?
  • Why is the area covered by 1 steradian (in a sphere) circular in shape?
  • Where to put acknowledgments in a math paper
  • Were the PS5 disk version console just regular digital version consoles with a pre-installed disk module?
  • Why was Esther included in the canon?
  • Time in Schwarzschild coordinates
  • How can I analyze the anatomy of a humanoid species to create sounds for their language?
  • Why was Panama Railroad in poor condition when US decided to build Panama Canal in 1904?
  • How can a microcontroller (such as an Arduino Uno) that requires 7-21V input voltage be powered via USB-B which can only run 5V?
  • Exam class: \numpages wrong when enforcing an even number of pages
  • How much could gravity increase before a military tank is crushed
  • MSSQL - query runs for too long when filtering after a certain date
  • Definition of annuity
  • Why are some Cloudflare challenges CPU intensive?
  • Should I write an email to a Latino teacher working in the US in English or Spanish?
  • How much technological progress could a group of modern people make in a century?
  • Why does Sfas Emes start his commentary on Parshat Noach by saying he doesn't know it? Is the translation faulty?
  • What is the rationale behind 32333 "Technic Pin Connector Block 1 x 5 x 3"?
  • Is Produce Flame a spell that the caster casts upon themself?

if statement assignment c

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

  • C Data Types
  • C Operators
  • C Input and Output
  • C Control Flow
  • C Functions
  • C Preprocessors
  • C File Handling
  • C Cheatsheet
  • C Interview Questions

C if else if ladder

if else if ladder in C programming is used to test a series of conditions sequentially. Furthermore, if a condition is tested only when all previous if conditions in the if-else ladder are false. If any of the conditional expressions evaluate to be true, the appropriate code block will be executed, and the entire if-else ladder will be terminated.

Working Flow of the if-else-if ladder:

  • The flow of the program falls into the if block.
  • The flow jumps to 1st Condition
  • If the following Condition yields true, go to Step 4.
  • If the following Condition yields false, go to Step 5.
  • The present block is executed. Goto Step 7.
  • If the following  Condition yields true, go to step 4.
  • If the following Condition yields false, go to Step 6.
  • If the following Condition yields true, go to step 4.
  • If the following Condition yields false, execute the else block. Goto Step 7.
  • Exits the if-else-if ladder.

if else if ladder in C

if else if ladder flowchart  in C

Note:  A if-else ladder can exclude else block.

Example 1: Check whether a number is positive, negative or 0

Example 2: Calculate Grade According to marks 

author

Please Login to comment...

Similar reads.

  • Best PS5 SSDs in 2024: Top Picks for Expanding Your Storage
  • Best Nintendo Switch Controllers in 2024
  • Xbox Game Pass Ultimate: Features, Benefits, and Pricing in 2024
  • Xbox Game Pass vs. Xbox Game Pass Ultimate: Which is Right for You?
  • #geekstreak2024 – 21 Days POTD Challenge Powered By Deutsche Bank

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

C Functions

C structures, c reference, c if ... else, conditions and if statements.

You have already learned that C supports the usual logical conditions from mathematics:

  • Less than: a < b
  • Less than or equal to: a <= b
  • Greater than: a > b
  • Greater than or equal to: a >= b
  • Equal to a == b
  • Not Equal to: a != b

You can use these conditions to perform different actions for different decisions.

C has the following conditional statements:

  • Use if to specify a block of code to be executed, if a specified condition is true
  • Use else to specify a block of code to be executed, if the same condition is false
  • Use else if to specify a new condition to test, if the first condition is false
  • Use switch to specify many alternative blocks of code to be executed

The if Statement

Use the if statement to specify a block of code to be executed if a condition is true .

Note that if is in lowercase letters. Uppercase letters (If or IF) will generate an error.

In the example below, we test two values to find out if 20 is greater than 18. If the condition is true , print some text:

We can also test variables:

Example explained

In the example above we use two variables, x and y , to test whether x is greater than y (using the > operator). As x is 20, and y is 18, and we know that 20 is greater than 18, we print to the screen that "x is greater than y".

C Exercises

Test yourself with exercises.

Print "Hello World" if x is greater than y .

Start the Exercise

Get Certified

COLOR PICKER

colorpicker

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: [email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail: [email protected]

Top Tutorials

Top references, top examples, get certified.

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

IMAGES

  1. 1.4. Expressions and Assignment Statements

    if statement assignment c

  2. Week 3 Assignment Mission Statement Analysis 2 .docx

    if statement assignment c

  3. Conditional Statements in C

    if statement assignment c

  4. C programming tutorials for Beginners

    if statement assignment c

  5. C# Nested If Statement

    if statement assignment c

  6. C programming tutorials for Beginners

    if statement assignment c

VIDEO

  1. Decision Making & Conditional Statement in C Language Part

  2. if else statement in c language

  3. Part 19. Nested If-Else Statement in C++ Programming || Exit Exam Course

  4. HLTH 2030 Summer '24 Philosophy Statement

  5. If Statement Assignment

  6. Thesis Statement Assignment for Narrative Essay

COMMENTS

  1. C assignments in an 'if' statement - Stack Overflow

    Your code is assigning data[q] to s and then returns s to the if statement. In the case when s is not equal to 0 your code returns s otherwise it goes to the next instruction. Or better said it would expand to the following: short s; s = data[q]; if (s != 0) return s;

  2. c++ - When would you want to assign a variable in an if ...

    C++17 added the ability to have an init-statement in the condition for an if statement , which solves this problem nicely (for kind of comparison, not just != 0). if (x = Foo(); x != 0) { ... } Furthermore, if you want, you can limit the scope of x to just the if statement: if (int x = Foo(); x != 0) { /* x in scope */ ... } // x out of scope

  3. C - if Statement - GeeksforGeeks

    The if in C is the most simple decision-making statement. It consists of the test condition and if block or body. If the given condition is true only then the if block will be executed.

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

    The if statement is the most simple decision-making statement. It is used to decide whether a certain statement or block of statements will be executed or not i.e if a certain condition is true then a block of statements is executed otherwise not. Syntax of if Statement. if(condition) . { // Statements to execute if // condition is true . }

  5. C if...else Statement - Programiz

    C if...else Statement. The if statement may have an optional else block. The syntax of the if..else statement is: if (test expression) {. // run code if test expression is true. } else {. // run code if test expression is false. }

  6. C if else if ladder - GeeksforGeeks

    Syntax: // any if-else ladder starts with an if statement only. if(condition) { . } else if(condition) { . // this else if will be executed when condition in if is false and. // the condition of this else if is true. } .... // once if-else ladder can have multiple else if . else { // at the end we put else . . }

  7. C If ... Else Conditions - W3Schools

    C has the following conditional statements: Use if to specify a block of code to be executed, if a specified condition is true. Use else to specify a block of code to be executed, if the same condition is false. Use else if to specify a new condition to test, if the first condition is false.

  8. C – If..else, Nested If..else and else..if Statement with example

    In this guide, we will learn how to use if else, nested if else and else if statements in a C Program. C If else statement. Syntax of if else statement: If condition returns true then the statements inside the body of “if” are executed and the statements inside body of “else” are skipped.

  9. If...Else Statement in C Explained - freeCodeCamp.org

    In an if...else statement, if the code in the parenthesis of the if statement is true, the code inside its brackets is executed. But if the statement inside the parenthesis is false, all the code within the else statement's brackets is executed instead.

  10. If Statement in C – How to use If-Else Statements in the C ...">If Statement in C – How to use If-Else Statements in the C ...

    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: if (condition) { // run this code if condition is true} Let's break it down: You start an if statement using the if keyword.