Перейти к содержимому

Statement в программировании что это

  • автор:

Разница между statement, expression и block(инструкция, выражение и блок)

Что такое statement, expression , block(инструкция, выражение и блок) и какая между ними разница ?

Выражение это фрагмент кода, результатом которого является некая величина. Инструкция фрагмент кода, изменяющий состояние окружения в котором выполняется программа.

Это определение взял из книги по javascript(http://eloquentjavascript.net/), думаю оно действует в контексте любого языка. Но всё же любопытно: насколько оно исчерпывающее.

Из определения следует:

  • sum = 2 + 3; — инструкция содержащая выражение
  • var sum; — просто инструкция без выражения
  • 2+3; — просто выражение, но выражения без инструкций бессмысленны(кроме случаев отладки) т.к. с результатом нужно что-то делать/где-то хранить его.

Блок — набор из нескольких инструкций.

Vsevolod's user avatar

Выражение(англ. Expression) — инструкция, присваивающая правую часть выражения левой части (выражает левую через правую).

Инструкция ( англ. Statement ) — в программировании, команда языка программирования, которым задается определенный шаг процесса обработки информации на ЭВМ.

1. Любое выражение — это инструкция.
2. Не каждая инструкция — выражение.

Блок(англ. Block) — это 0 или больше инструкций помещенных между фигурными скобками и может быть помещен в том месте кода, где это дозволяется. Например:

Statement vs Expression – What's the Difference in Programming?

Ogundiran Ayobami

Ogundiran Ayobami

Statement vs Expression – What's the Difference in Programming?

Learning the syntax of a programming language is key if you want to use that language effectively. This is true for both new and experienced developers.

And one of the most important things to pay attention to while learning a programming language is whether the code you’re dealing with is a statement or an expression.

It can sometimes be confusing to differentiate between statements and expressions in programming. So this article is meant to simplify the differences so that you can improve your programming skills and become a better developer.

What is an Expression in Programming?

Senior caucasian man holding blank empty banner covering mouth with hand, shocked and afraid for mistake. surprised expression

Photo by krakenimages / Unsplash

An expression is any word or group of words or symbols that is a value. In programming, an expression is a value, or anything that executes and ends up being a value.

It is necessary to understand that a value is unique. For example, const , let , 2 , 4 , s , a , true , false , and world are values because each of them is unique in meaning or character.

Let’s look at some code as an example:

Judging from the code above, const , price , = , and 500 are expressions because each of them has a definite and unique meaning or value. But if we take all of them together const price = 500 — then we have a statement.

Let’s look at another example:

Looking at the code above, you can see an anonymous function is assigned to a variable. Oh, wait! You might know that any function is a statement. Can it also be an expression?

Yes! A «function» and a «class» are both statements and expressions because they can perform actions (do or not do tasks) and still execute to a value.

This brings us to statements – so what are they?

What is a Statement in Programming?

A statement is a group of expressions and/or statements that you design to carry out a task or an action.

Statements are two-sided – that is, they either do tasks or don’t do them. Any statement that can return a value is automatically qualified to be used as an expression. That is why a function or class is a statement and also an expression in JavaScript.

If you look at the example of the function under the section on expressions, you can see it is assigned and execute to a value passed to a variable. That is why it is an expression in that case.

Examples of Statements in Programming

Inline statements

The whole of the code above is a statement because it carries out the task of assigning $2000 to amount . It is safe to say a line of code is a statement because most compilers or interpreters don’t execute any standalone expression.

Happy man portraits

Photo by Nimi Diffa / Unsplash

Block statements

Look at the below if statement:

The if statement is a statement because it helps us check whether I love you or not. As I have said before, it is two-sided: this code finds out whether «I love you» or not, and that is why it is a statement. Also, it doesn’t return any value but it can create side effects.

Here’s a loop statement:

In short, any loop is a statement because if it can only do the tasks it is meant to do or not – does loop and doesn’t loop. But a loop can’t execute to a value in the end. They can only have side effects in JavaScript. Once they can execute to a value in a programming language, then they can also be used as an expression.

For example, you can use forloop and if statement as expressions in Python.

There is also an «IF» expression in Python. That means that something that is a statement in one language can be an expression (or both statement and expression) in another.

Look at the below function statement:

We declare the function add(firstNumber, secondNumber) and it returns a value. The function is called with two arguments as in add(2, 3) by declaration and so it is a statement. If you pay close attention, you will realize that calling the function as a statement is useless since it has no side effect.

Hey, stop! How can we turn it into an expression? Oh yeah, we can do it like this:

Though the function is now an expression the way it is called above, the whole of the code is still a statement.

Check out this class statement:

You can see that we declare the class «Person» and instantiate and assign it to «User» immediately. So, it is used as an expression.

Now, let’s use it as a statement:

A class is similar to a function in the sense that it can be declared, assigned, or used as an operand just like a class. So, a class is a statement and/or an expression.

The Main Differences Between an Expression and a Statement in Programming

Expressions can be assigned or used as operands, while statements can only be declared.

Statements create side effects to be useful, while expressions are values or execute to values.

Expressions are unique in meaning, while statements are two-sided in execution. For example, 1 has a certain value while go( ) may be executed or not.

Statements are the whole structure, while expressions are the building blocks. For example, a line or a block of code is a statement.

Why You Should Know the Difference

First of all, understanding the difference between statements and expressions should make learning new programming languages less surprising. If you’re used to JavaScript, you may be surprised by Python’s ability to assign an if statement as a variable which is not possible in JavaScript.

Second, it makes it easy to use programming paradigms across different programming languages.

For example, a JavaScript «if statement» cannot be used as an expression because it can’t execute to a value – it can only create side effects. Yet, you can use the ternary operator if you want to avoid the side effects of using an if statement in JavaScript.

For this reason, you can understand why some programmers avoid if statements by using the ternary operator in JavaScript. It is because they want to avoid side effects.

It also makes your realize why you have to be always careful about the scope of your variables whenever you use a statement. This is true because statements mostly have side effects to be useful, and it is reasonable to understand the scope of your variables and operations. For example,

Hey wait! What would be logged in the console if you ran the code above?

Tell yourself the answer first and then paste the code in the console to confirm. If you you’re wrong, you need to learn more about scope and side effects. But if you’re right, try to make those functions a bit better to avoid the confusion they may generate.

Knowing the difference also helps you to easily identify non-composable and composable syntaxes (functions, classes, modules, and so on) of a programming language. This makes porting your experience from one programming language to another more interesting and direct.

Wrapping Up

Now that you understand the difference between expressions and statements in programming, and you know why understanding the differences is important, you can identify pieces of code as expressions or statements while coding.

Next time, we’ll go even further and help make learning a second programming language easier.

Go and get things done now! See you soon.

I am planning to share a lot about programming tips and tutorials in 2023. If you’re struggling to build projects or you want to stay connected with my write-ups and videos, please join my list at YouTooCanCode or subscribe to my YouTube channel at You Too Can Code on YouTube.

Как правильно перевести термины Statement и Declaration?

Я перевожу статью по ST. В ней есть 2 термина statement и declaration. Я прекрасно понимаю, что это разные понятия. Например, вот, declaration программы:

А вот statement:

К сожалению я на русском мало читал технических статей, и мой запас терминов на русском — слабый. Как правильно перевести эти 2 термина? У меня в голове одно и тоже слово для 2х этих терминов.

  • Вопрос задан более трёх лет назад
  • 3159 просмотров
  • Facebook
  • Вконтакте
  • Twitter

neurocore

  • Facebook
  • Вконтакте
  • Twitter

neurocore

Declaration — объявление
Statement — команда

По моему не плохо подходит

EgoRusMarch

EgoRusMarch

  • Statement — инструкция (дословно как «заявление»). Это всё, что заканчивается точкой с запятой (;) или является управляющей конструкцией (но не само ключевое слово)
  • Operator — оператор. Это: +, —, /, *, =, >, <, ==, &&, ||. А также ключевые слова: if, for, while, return, continue, break, goto. Но это уже statements:
    • for (init;condit;modif) < . >
    • return value;
    • result = op_1 + op_2;
    • Facebook
    • Вконтакте
    • Twitter
    • Facebook
    • Вконтакте
    • Twitter

    Оператор — это перевод и для Operator и для Statement. Имеет разное значение в зависимости от контекста.

    Например, в переводе C# Language Specification, п.1.5 Statements переведен как оператор:
    «The actions of a program are expressed using statements. C# supports several different kinds of statements, a number of which are defined in terms of embedded statements . » => «Действия программы выражаются с помощью операторов. В C# поддерживается несколько различных типов операторов, некоторые из которых определяются как внедренные операторы. . «.
    А в п.1.4 Expressions:
    «Expressions are constructed from operands and operators. The operators of an expression indicate which operations to apply to the operands. Examples of operators include +, -, *, /, and new. » = > «Выражения состоят из операндов и операторов. Операторы в выражении указывают, какие операции производятся с операндами. К операторам относятся, например, +, -, *, / и new. «

    Statement -> инструкция;
    Declaration -> объявление.

    Другие варианты перевода statement будут конфликтовать с одним из терминов declaration (объявление), definition (определение), operator (оператор) или expression (выражение).

    • Facebook
    • Вконтакте
    • Twitter
    • Facebook
    • Вконтакте
    • Twitter

    Ну есть еще декларирование функций и фукциональных блоков.

    Хотя команда это хороший перевод для statement.

    Александр Скуснов, согласен нужно по смыслу. Я думаю что если в начале четко определить терминологию, читателю все будет понятно, главно что бы он понимал что под тем или иным термином имеется в виду, даже если в других статьях о других языках этот термен имеет немного другое значение.

    По Акшенам, они не только в SFC они есть в любой программе. Можно и в ST программе создать акцию. Но это скорей фича IDE чем сам стандарт. Короче по этому пока вопросов нет у меня.

    Chapter 2 : Understanding Tools

    Saketh G

    Until now, we have learnt various topics in programmming. But if we observe carefullyu, all these topics are pretty much atomic concepts, i.e., we have learnt what inputs are , what data types are, what are the operators but we have yet to learn how to use all these building blocks to write a program. Well we are getting into to it, this section of the chapter will pave an introduction to it.

    2.2 Statements

    A statement is a command that the programmer gives to the computer. So basically we write bunch of statements as a program, which then followed by computer step by step to perform the necessary task. Let us look at few examples:

    In the above example, each line is a statement. Each line tells the computer to perform a simple task.

    • In line 1, we are adding 10 and 20 using + operator and then assigning the sum to a variable named a.
    • In line 2, we are multiplying 10 and 20 using * operator and then assigning the product to a variable named b.
    • In line 3, we are subtracting the variables a and b and then assigning the result to another variable named c.

    The above statements are simple examples of assignment statements. An instruction which assigns a value to a variable or a constant is called an assignment statement.

    Any instruction that performs certain action is called a statement in programming and there are various types of statements, in addition to the assignment statement. The most common types of statements are Conditional Statements and Looping statements. We will cover Conditional statements in this tutorial and will cover Looping statements in the next tutorial.

    2.2.1 Conditional Statements

    Statements which introduces a condition in the program are called conditional statements. With the help of these statements we can ask program to execute certain statements only of the condition represented by a conditional statement is True. Confusing? Let us understand with an example.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *