if(true/false){
//if condition is true
}else {
// if condition is false
}
Everyone knows about the structure of if-else
. But what is if
actually? Is it a class method, static method or keyword? I'm little confused about this.
Software Engineering Stack Exchange is a question and answer site for professionals, academics, and students working within the systems development life cycle. It only takes a minute to sign up.
Sign up to join this communityif(true/false){
//if condition is true
}else {
// if condition is false
}
Everyone knows about the structure of if-else
. But what is if
actually? Is it a class method, static method or keyword? I'm little confused about this.
It seems to me that you are asking two different questions:
if else
works internally?if
is in terms of high level programming?This answer is for question 1. For question 2 see other answers. Gustav Bertram's answer seems very clear.
Before your code gets executed, it must be translated into machine code. The translation is done by either a compiler (like a C-compiler) or an interpreter (like Ruby interpreter) or a virtual machine (like with Java).
Control structures like if-else are translated into a pattern of machine code instructions. The actual pattern depends on the target machine and the compiler/interpreter/virtual machine. An if-else-structure like
if (x >= y) {
// main branch
} else {
// else branch
}
could be translated into code (here some kind of pseudo-assembly) like
cmp (r1),(r2) ;compare words at memory addresses pointed by registers r1 and r2
blt else ;jump to else-part if (r1) is less than (r2)
... ;insert the main branch code here
bra end_if ;jump to end_if
else:
... ;insert the else branch code here
end_if:
The actual machine code consists of just binary data but it is structurally similar with assembly code.
if(condition) goto ifcode; <else code>; goto end; ifcode: <if code>; end:
This answer is about languages like C, C++, Java, PHP and Javascript. There are other programming languages that work differently.
if
is a keyword, and else
is a keyword. When they are used in code, if
and else
together form a control flow statement.
Class methods, or static methods are always functions or procedures that are attached to a class. "Method" means the same thing as "function" or "procedure", but on a class.
if else
is not a function, but it can appear inside a function.
# This part is a function, and *could* be a class method or static method
function hello($name)
{
# This part is a control flow statement, and can be *inside* a function
if($name=='Peter')
{
#The next line is one statement
echo 'Hello Pete!";
} else {
echo 'Hello $name!";
}
}
These are examples of keywords: if
, else
, while
, for
, case
, continue
, function
, return
, class
, public
, private
, protected
, static
, new
.
Each programming language has different keywords. What your keywords are, and how they work are different in every language.
Keywords (if
, else
), operators (==
, <
, !=
), variables ($name
), string literals ('Peter'
), functions (echo
, hello
) all work together to make statements. Statements do all most of the work, and are grouped into functions or methods (usually).
I think you should try Code Academy. It teaches basic programming, and it might help you understand the parts of programming statements.
You should also try to find a book that teaches your programming language. Such books should explain the parts of statements too. If one book is not clear, try another one.
if
is" in terms of high level programming. My answer is about how if
is implemented or how "it works internally" like the title of the question seems to ask.
Feb 15, 2013 at 9:58
statements do all the work
, sorry, with all due respect, this is BS. There are even languages that do not have statements
, yet the work
is done nevertheless.
It can actually be several things. In imperative languages like C++ or Java, it is a statement type. In pure object-oriented languages like Smalltalk it is an instance method of boolean. In pure functional languages it is a function.
But in all languages it is a primitive. Some form of conditional must be built into the language. It may be slightly different type of conditional (e.g. cond
in Lisp), but one must be built in.
As the others have already explained, control flow is usually implemented with branching instructions.
But, jumps are not always necessary. In some ISAs there is a so called "conditional execution": instructions will be bypassed if they're marked as conditional and a flag after a previous comparison operation is not set. Jumps can be mispredicted and may thrash pipeline, whereas a short sequence of conditional instructions might be much cheaper.
Another interesting form of low level control flow is a so called "zero-overhead looping", common in many modern DSP processors (e.g., in Hexagon).
Internally on x86/64 architecture if/else/then is generated with internal CMP mnemonic.
It compares the results and sets the EFLAGS register with appropriate flags(zero, overflow, etc.).
Internally if the arguments are equal their minus product is zero. For example
if (a == b)
where a = 10, b = 10. Processor does 10-10=0. Once the result is zero - ZF(Zero Flag) is set.
So:
cmp a, b
jz equal
jnz notEqual
JZ - Jump if Zero is equal to JE as well as JNZ(Not Zero) is equal to JNE(Not Equal). They are equal and JE and JNE exist just because of readability.
It really depends on the language, of course. Since you're giving a pseudo-C example, I'll stick to how it works in most C-like languages.
A program has to be translated to machine-code in the end, so we have to talk about machine code first.
Let's start with an (imaginary, but that's the idea) very old computer who is able to perform these operations only :
So, the following "program" saved on, say, a punched card :
Would put a number in A, then another in B, add them and put the result in A then print it on a piece of paper. The point is, very old computers did not have any possibility of conditional execution or loops. A program was nothing more than perform this calculation, then this one, then this one, and so one. They were little more than a calculator to which you gave a list of calculations to perform.
That soon became a problem : very often, we want a calculation not to be performed in some situations ; for example, if the current value is 0, I don't want to divide another number by it ! Computers had to be enhanced, and that was a big and (somewhat) complicated improvement : now, your computer has to be aware of where it is in the current program flow and act on it ; just reading the current instruction and going to the next one is not enough.
That means you have to add the following instructions to go forward :
Very good, now you can skip instructions if needed ; for example, you can skip the division instruction if you do not want to perform it. Well, actually, we will always jump, so that's a rather useless statement. Let's rewrite it this way :
Yep, an "if statement", that's where it is actually implemented : in a machine instruction. It's very low level and limited, but that's actually not a problem because you can do anything you want with it. It's hard to use, but high-level languages will deal with that for you. Note that it is really very powerful : you can implement loops with it, too (loops are a jump backward rather than forward).
Let's write the following program : read two numbers, subtract them. If the result is not 0, read a third number, divide it by the result and print the overall result.
Well, that's rather boring to write programs this way, so assembly languages were invented :
And, since assembly is dull and error-prone too, we invented high-level languages such as C. The following pseudo-C program is the equivalent as above :
a = read();
b = read();
a = a - b;
if (a != 0) {
b = read();
a = a / b;
}
print(a);
The way if
is translated by your compiler in machine instructions : the condition after the if
keyword is transformed as a test whose result is stored in A, and the number of the instruction where to jump is determined based on where your bracket closes.
Once you get down to the metal, it is a jump/branch statement -- basically a fancy goto. Higher level languages have control structures that let you implement common low level activities in a clear and understandable manner. But when you get down to it, it's a bunch of registers, jumps and poking things in and out of memory.
This in fact depends on the language you are talking about.
There are excellent answers here on how if
and else
are keywords and form control flow statements because when compiled to a sequence of instructions, these statements control the execution flow of the instruction sequence - which of course is sequential by default, but can have jumps in order to allow execution to depend on the current state. And this is certainly true for a whole set of languages.
But there are a couple of languages, such as Smalltalk and Lisp (probably the most prominent examples), that actually implement their equivalent of control flow statements as methods or macros respectively, over a very basic mechanism for conditional execution/jumps.
cond
, tagbody
and go
do the trick. A tagbody
and goif
would be enough to construct cond
. Or you can also compose branching from loops and sequences alone. But all that is an implementation detail.
macros
per se are not an underlying implementation mechanism. There is usually a set of simple primitives and a number of higher level macros expanding into such primitives.
implement their equivalent of control flow statements as methods or macros respectively, over a very basic mechanism for conditional execution/jumps.
whether that "basic mechanism" as I called it is in fact a set of first class primitives (as in most Lisp implementations) or somehow hacked into the language (as in many Smalltalk implementations) tends to vary.