Unreachable code is code that can never be executed because program control cannot reach it during normal execution.
- C++ compilers may detect unreachable code and issue a warning.
- Code after an unconditional return statement is a common example of unreachable code.
Example: If a function executes return and then has more statements, those statements cannot be executed because the function has already ended.
return -> Function ends -> Code below return -> Unreachable
Approach
The program follows these steps:
- Define a function c() and initialize a variable a with 3.
- Return the value of a using the return statement.
- Write two more statements after return.
- Since return immediately terminates the function, these statements can never be executed.
- Call c() from main() and print the returned value.
#include <iostream>
using namespace std;
int c()
{
int a = 3;
return a;
// Unreachable code
int b = 6;
cout << b;
}
int main()
{
cout << c() << endl;
return 0;
}
Output
3
Explanation
- return a; immediately ends c() and returns 3.
- The statements after return can never execute, so they are unreachable code.
- main() prints the value returned by c(), resulting in 3.