12

It's almost midnight and I just got a question in my head is "for loop" a statement or a function.

I always thought it is a statement, but I did a google search on it being a function and there are indeed results for that. So what is it? And in that case what is the difference between function and statement?

Sasha Kolsky
  • 432
  • 1
  • 5
  • 14
  • That really depends on your language. What is it, Ruby, Python or Javascript? – deceze Feb 16 '12 at 07:42
  • 1
    Good question--it shows you've done your research, which is huge. – Purag Feb 16 '12 at 07:43
  • @deceze aren't they all statements in these three languages? – Corey Farwell Feb 16 '12 at 07:52
  • 1
    @Corey If I remember correctly, virtually everything in Ruby is an expression. Further, the most idiomatic way to loop in Ruby is usually using methods of an object. But since the question itself doesn't specify a language, I guess this is meant to be language-independent, in which case you'll find a lot of languages where it can be none of the above. – deceze Feb 16 '12 at 07:57

3 Answers3

19

A for loop is a not usually a function, it is a special kind of statement called a flow control structure.

A statement is a command. It does something. In most languages, statements do not return values. Example:

print "Hello World"

A function is a subroutine that can be called elsewhere in the program. Functions often (but not necessarily) return values. Example:

function(a) { return a * 2 }

A control structure, also known as a compound statement, is a statement that is used to direct the flow of execution. Examples:

if (condition) then { branch_1 } else { branch_2 }
for (i = 0; i < 10; i += 1) { ... }

Also worth noting is that an expression is a piece of code that evaluates to a value. Example:

2 + 2

All examples are in pseudocode, not tied to any particular language. Also note that these are not exclusive categories, they can overlap.

vallentin
  • 23,478
  • 6
  • 59
  • 81
Ben Lee
  • 52,489
  • 13
  • 125
  • 145
  • 1
    By that logic, then, a `for` loop would be both a statement *and* a control structure, yes? And a function doesn't *need* to return something--it too can be used to simple execute, but in a manner in which certain things are variable and the product is based on specific circumstances. – Purag Feb 16 '12 at 07:44
  • It is incorrect to say that a for loop is neither a statement nor a function (not that it isn't used as a control structure). A for loop is a compound statement in most languages, although it can be an expression or function as well. In Javascript, Python and Ruby it is a statement. – Zach Kelling Feb 16 '12 at 07:49
  • @Purmou, I was in the process of updating my answer to fix that just as you posted a comment. – Ben Lee Feb 16 '12 at 07:51
  • And yes, these are not exclusive categories, they can overlap. – Ben Lee Feb 16 '12 at 07:52
  • In Ruby, `for` is an expression as well, as it returns the `Enumerable` iterated. Also, it is really rarely used, usually the loops are performed using `each` method. – Mladen Jablanović Feb 16 '12 at 11:35
  • @MladenJablanović, yes I'm aware (Ruby is my primary development language). I was just trying to cover the basic terminology so as not to confuse someone unfamiliar. In Ruby nearly everything is an expression, after all (there a couple very rare exceptions to that in Ruby). – Ben Lee Feb 16 '12 at 17:03
  • What is the difference between a compound statement and a function ? – madLokesh May 07 '15 at 07:14
  • @madLokesh, "compound statement" is just another name for "control structure". It's just a statement that controls execution flow (it's called "compound" because it's different than plain statements -- control structures have bodies that are turn composed of more statements). – Ben Lee May 07 '15 at 18:04
  • Due to [compound statements](https://docs.python.org/3/reference/compound_stmts.html) doc, "Function and class definitions are also syntactically compound statements." –  Jul 18 '20 at 09:40
  • @zeekay, you said it is incorrect to say a for loop is not a function. Will you provide an example of a for loop which is a function? – Georgina Davenport Mar 07 '21 at 12:25
  • @Purag, you state a function need not return something. It is my understanding, via computer science, that the definition of a function is it produces a mapping from one set to another, from a domain to a unitary value in a range. – Georgina Davenport Mar 07 '21 at 12:29
  • 1
    @GeorginaDavenport The definition of a function as a mapping from a domain to a range is more of a strictly mathematical definition. In computer science "function" is often just used as a synonym of "subroutine", which may or may not return any value, depending on the language. Plus unlike a mathematical function, in most languages there is no restriction that a given input will always return the same output. In fact, for some functions that is their express purpose (e.g. a "Time.now()" function might return a different value depending on the time of day). – Ben Lee Mar 19 '21 at 15:08
  • I'm not sure if I agree with your statement that a function is a synonym for a subroutine. It is my understanding that in computer programming (not computer science, which I would say is not the same thing) a function is similar to the set theoretical kind in that it always returns a single value, usually a type. If that thing is a changing value such as time then be that as it may. A subroutine by contrast needn't return any value. This is how it is in Fortran where functions and subroutines are two separate types of construct. – Georgina Davenport Mar 20 '21 at 00:29
8

Out of the three language tags you've chosen, I'm only very familliar with Python, but I believe many other languages have a similar view of these concepts. All the example code here is Python.

A statement is a thing that is executed; an "instruction to do something" that the language implementation understands. e.g.

print "Hello World"

pass

def foo(n):
    return n + 1

if condition:
    print 'yay'
else:
    print 'doh'

The above block contains a print statement, a pass statement, a function definition statement, and an if/else statement. Note that the function definition and the if/else statement are compound statements; they contain other statements (possibly many of them, and possibly other compound statements).

An expression is something that can be evaluated to produce a value. e.g.

1

"foo"

2 * 6

function(argument)

None

The above contains a numeric literal expression, a string literal expression, an expression involving numeric operators, a function call expression, and the literal None expression. Other than literals and variables, expressions are made up of other expressions. In function(argument), function and argument are also both expressions.

The key difference is that statements are instructions that tell the language implementation to "go do something". Expressions are evaluated to a value (which possibly requires to language implementation to "go do something" on the way).

A consequence of this is that anywhere you see a value (including an expression), you could substitute any other expression and you would still get something that makes some sort of sense. It may fail to compile, or throw exceptions at runtime, or whatever, but on at least some level you can understand what's going on.

A statement can never appear inside an expression (I believe this is not true in Ruby and Javascript in some sense, as they allow literal code blocks and functions which are then used as a value as a whole, and functions and code blocks contain statements; but that's kind of different from what I'm talking about). An expression must have a value (even if it's an uninteresting one like None). A statement is a command; it doesn't make sense for it to appear as part of an expression, because it has no value.

Many languages also allow expressions to be used as statements. The usual meaning of this is "evaluate this expression to get a value, then throw it away". In Python, functions that always return None are usually used this way:

write_to_disk(result)

It's used as a "command", so it looks like a statement, but technically it's an expression, we just don't use the value it evaluates to for anything. You can argue that a "bare expression" is one of the possible statements in a language (and they're often parsed that way).

Some languages though distinguish between functions that must be used like statements with no return value (often called procedures) and functions that are used like an expression, and give you errors or warnings for using a function like a statement, and definitely give you an error for using a procedure as an expression.

So, if foo is an expression, I can write 1 + foo and while it may be result in a type error, it at least makes that much sense. If foo is a statement, then 1 + foo is usually a parse error; the language implementation won't even be able to understand what you're trying to say.


A function on the other hand, is a thing you can call. It's not really either an expression or a statement in itself. In Python, you use a def statement to create a function, and a function call is an expression. The name bound to the function after you create it is also an expression. But the function itself is a value, which isn't exactly an expression when you get technical, but certainly isn't a statement.


So, for loops. This is a for loop in Python:

for thing in collection:
    do_stuff(thing)

Looks like a statement (a compound statement, like an if statement). And to prove it, this is utterly meaningless (and a parse error):

1 + for thing in collection:
    do_stuff(thing)

In some languages though, the equivalent of a for loop is an expression, and has a value, to which you can attempt to add 1. In some it's even a function, not special syntax baked into the language.

Ben
  • 68,572
  • 20
  • 126
  • 174
  • "A statement can never appear inside an expression (I believe this is not true in Ruby […])" – Ruby doesn't have statements, only expressions. – Jörg W Mittag Feb 16 '12 at 13:25
  • @JörgWMittag What's the value of a for loop then? After quick google of Ruby syntax doesn't *look* like it has a value, except in the sense of being a code block. An expression that evaluates to "code value" and a statement to be executed do seem to be different things, even if the same raw text in the source code could represent either depending on the context; I'm grappling with this issue right now in a toy language I'm idly developing. – Ben Feb 18 '12 at 01:26
  • @JörgWMittag I've done some more reading, and I see that that's not what you're talking about at all. Ruby does give values to loops and conditionals and such. Neat! However there's still some things that really are *semantically* statements, such as `break` (and it appears sometimes Ruby gives you a parse error for using them as expressions, though not always: http://carboni.ca/blog/p/Statements-in-Ruby) – Ben Feb 18 '12 at 01:41
1

This answer is relevant to Python 2.7.2. Taken from the python tutorial:

"4. More Control Flow Tools

4.2. for Statements: The for statement in Python differs a bit from what you may be used to in C or Pascal. Rather than always iterating over an arithmetic progression of numbers (like in Pascal), or giving the user the ability to define both the iteration step and halting condition (as C), Python’s for statement iterates over the items of any sequence (a list or a string), in the order that they appear in the sequence."

Zain Khan
  • 3,753
  • 3
  • 31
  • 54