49

Interesting discussion came up among my peers as to whether or not the "if" statement is considered a method? Although "if" is appended with the word statement it still behaves similar to a simple non-return value method.

For example:

if(myValue) //myValue is the parameter passed in
{
    //Execute
}

Likewise a method could perform the same operation:

public void MyMethod(myValue)
{
    switch(myValue)
    {
        case true:
            //Logic
            break;
        case false:
            //Logic
            break;
    }
}

Is it accurate to call (consider) the "if" statement a simple predefined method in a programming language?

6
  • No, I would never think of it that way. It's a control statement, built into the language. I'll be surprised if anyone else agrees with you.
    – duffymo
    Commented Dec 29, 2011 at 21:38
  • 3
    public int five() { return 5; } // does that mean 5 is a method ?
    – yurib
    Commented Dec 29, 2011 at 21:42
  • 2
    I wouldn't even consider it to be a function, not too talk of being equivalent to a method. This is beer tower intellectualism at work.
    – Perception
    Commented Dec 29, 2011 at 21:48
  • 5
    This is the reason why I think consider writing if(x) bad coding style. It "looks" a lot like a function call, even though it isn't. Same for for(...) and while(..). Commented Dec 30, 2011 at 6:28
  • 2
    From your logic, switch() should be a method too, after all you could just do a method that performed the same operation (maybe using if? :))
    – djeidot
    Commented Jan 5, 2012 at 9:17

14 Answers 14

104

In languages such as C, C++, C#, Java, IF is a statement implemented as a reserved word, part of the core of the language. In programming languages of the LISP family (Scheme comes to mind) IF is an expression (meaning that it returns a value) and is implemented as a special form. On the other hand, in pure object-oriented languages such as Smalltalk, IF really is a method (more precisely: a message), typically implemented on the Boolean class or one of its subclasses.

Bottom line: the true nature of the conditional instruction IF depends on the programming language, and on the programming paradigm of that language.

3
  • 2
    @Oscar: Yep, it's a special form, sorry. I just stumbled upon the term expression. Almost everything is an expression in LISP. But yeah, this is 100% correct.
    – Niklas B.
    Commented Mar 28, 2012 at 21:51
  • 3
    @Oscar: if-then-else can also be represented as message-passing in the Actor model (en.wikipedia.org/wiki/Actor_model_and_process_calculi_history).
    – gfour
    Commented Apr 18, 2012 at 9:23
  • 1
    Here's a "dialect" of Lisp where if is not a special form: thimbleby.net/misc (Hint: MISC uses lazy evaluation.) ;-) Commented Jun 24, 2013 at 12:49
42

No, the "if" statement is nothing like a method in C#. Consider the ways in which it is not like a method:

  • The entities in the containing block are in scope in the body of an "if". But a method does not get any access to the binding environment of its caller.
  • In many languages methods are members of something -- a type, probably. Statements are not members.
  • In languages with first-class methods, methods can be passed around as data. (In C#, by converting them to delegates.) "if" statements are not first-class.
  • and so on. The differences are myriad.

Now, it does make sense to think of some things as a kind of method, just not "if" statements. Many operators, for instance, are a lot like methods. There's very little conceptual difference between:

decimal x = y + z;

and

decimal x = Add(y, z);

And in fact if you disassemble an addition of two decimals in C#, you'll find that the generated code actually is a method call.

Some operators have unusual characteristics that make it hard to characterize them as methods though:

bool x = Y() && Z();

is different from

bool x = And(Y(), Z());

in a language that has eager evaluation of method arguments; in the first, Z() is not evaluated if Y() is false. In the second, both are evaluated.

Your creation of an "if" method rather begs the question; the implementation is more complicated than an "if" statement. Saying that you can emulate "if" with a switch is like saying that you can emulate a bicycle with a motorcycle; replacing something simple with something far more complex is not compelling. It would be more reasonable to point out that a switch is actually a fancy "if".

0
14

You can't create a myIfStatement() method and expect the following to work:

...
myIfStatement(something == somethingElse)
{
   // execute if equal
}
else
{
   // execute if different
}

if is a control statement, and cannot be replicated by a method, nor can you replace a method call with if:

myVariable = if(something == somethingElse);

if cannot be overloaded.

These are a few signs that if is not a method, but there are others I suspect.

8

Depends on the language for sure, but in C, java, perl, no, they're language commands. Reserved words. If they were functions, you'd be able to overload them and get pointers to them and do all the other things that you can do with functions.

This is more of a philiosophical question than a programming question though.

3
  • 1
    also functions return data. if and switch do not. Looking less and less like a function the more I think about it. You can't pass it to another function as a parameter either.
    – stu
    Commented Dec 29, 2011 at 21:39
  • But a method that includes void doesn't return a value either.
    – Edward
    Commented Dec 29, 2011 at 21:40
  • 1
    that doesn't make it not a function. That makes it a function that doesn't return anything. In all other respects it is still a function (getting a pointer, etc) whereas a language command is not.
    – stu
    Commented Dec 29, 2011 at 21:44
4

A method has a signature and its main intention is resuable logic, whereas if is simply a condition that controls the flow of execution. If you understand assembly, you would know that both are different even on a very low level.

3

You can of course write If() and IfElse() methods but that does not make them the same.

if() is defined as a statement in the language , at the same level as method calls. But there are differences in a.o. syntax and optimization possibilities.

So: No, the if() statement is not a method. You cannot for instance not assign it to a delegate.

3

Considering the if statement to be a method only makes it confusing, in my opinion. The similarities with a method call is just superficial.

The if statement is one of the statements that control the execution flow. When it's compiled into native machine code, it will evaluate the expression and make a conditional jump.

Pseudo code:

load myValue, reg0
test reg0
jumpeq .skip
  ; code inside the if
.skip:

If you use else, you will get two jumps:

load myValue, reg0
test reg0
jumpeq .else
  ; code inside the if
  jmp .done
.else:
  ; code inside the else
.done:
3

Is the “if” statement considered a method?

No, it's not considered a method as you may have already seen in the other answers. However, if your question were - "Does it behave like a method?", then the answer could be yes depending on the language in question. Any language that supports first-class functions could do without an in-built construct/statement like if. Ignore all the fluffy stuff like return values and syntax, as basically it is just a function that evaluates a boolean value and if it is true, then it executes some block of code. Also ignore OO and functional differences because the following examples can be implemented as a method on the Boolean class in whatever language is being used like Smalltalk does it.

Ruby supports blocks of executable code that can be stored in a variable and passed around to methods. So here's a custom _if_ function implemented in Ruby. The stuff within the { .. } is a piece of executable code that's passed to the function. It's also known as a block in Ruby.

def _if_ (condition)
  condition && yield
end

# simple statement
_if_ (42 > 0) { print "42 is indeed greater than 0" }

# complicated statement
_if_ (2 + 3 == 5) {
    _if_ (3 + 5 == 8) { puts "3 + 5 is 8" }
    _if_ (5 + 8 == 13) { puts "5 + 8 is 13" }
}

We can do the same thing in C, C++, Objective-C, JavaScript, Python, LISP, and many other languages. Here's a JavaScript example.

function _if_(condition, code) {
    condition && code();
}

_if_(42 > 0, function() { console.log("Yes!"); });
2

If it were to be classed as a method then surely we would be in the realms of OO, however we're not, so I'll assume we're on about a function. Certainly a function/subroutine could be written to replicate the if behaviour (I think it is actually a function in lisp/scheme).

I wouldn't class it as a function or even a subroutine though, just control flow.

2

If by method we understand a block of code that could be called and the control flow automatically returns to the caller when the method ends, then ifs aren't methods. The control flow doesn't return anywhere after an if is executed.

2

The IF statement is a conditional contruct feature used in most lanuages which executes a path flow from the boolean condition evaluation of true or false. Apart from the case of branch predication, this is always achieved by selectively altering the control flow based on some condition.

The IF construct is the most basic and needed logic used when programming. It allows the building blocks for functions to be introduced.

2

Yes, if is a function in certain languages, even though it's rare and the uses are limited.

Usually the construct is something like if(booleanCondition, functionPointerToCallIfConditionTrue, functionPointerToCallIfCondtionFalse) This can itself be used as a delegate to other functions if you want.

Mathematica, for example, behaves this way and even C# can do so with a bit of work if you use Linq-expressions; Take a look at System.Linq.Expressions.Expression.IfThenElse.

0

No. You don't return back when you are finished with an if. It's merely a control statement.

0

Note that in your example, you replaced one "selection statement" (C# 4 specification, section 8.7), the if statement (section 8.7.1) with another, the switch statement (section 8.7.2). You also refactored the selection statement into a separate method. You haven't replaced the use of a selection statement with a method, however.

The answer to your question is "no".

0

Not the answer you're looking for? Browse other questions tagged or ask your own question.