Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is variable assignment a statement or expression?

I am familiar that statements do something and that expressions are a "collection of symbols that make up a quantity" (What is the difference between an expression and a statement in Python?). My question is: when you assign a value to a variable is that assignment a statement or an expression?

For example (in C):

int x = 5;
like image 623
Darien Springer Avatar asked Sep 23 '17 01:09

Darien Springer


People also ask

What is a variable assignment?

Variable Assignment To "assign" a variable means to symbolically associate a specific piece of information with a name. Any operations that are applied to this "name" (or variable) must hold true for any possible values.

Is assignment a statement or expression in Python?

An assignment statement evaluates the expression list (remember that this can be a single expression or a comma-separated list, the latter yielding a tuple) and assigns the single resulting object to each of the target lists, from left to right.

What is the difference between expression and assignment statement?

In programming language terminology, an “expression” is a combination of values and functions that are combined and interpreted by the compiler to create a new value, as opposed to a “statement” which is just a standalone unit of execution and doesn't return anything.


1 Answers

Well, when you say

int x = 5;

that's a declaration, that happens to include an initialization.

But if you say

x = 5

that's an expression. And if you put a semicolon after it:

x = 5;

now it's a statement.

Expression statements are probably the most common type of statement in C programs. An expression statement is simply any expression, with a semicolon after it. So there are plenty of things that might look like some other kind of statement, that are really just expression statements. Perhaps the best example is the classic

printf("Hello, world!\n");

Many people probably think of this as a "print statement". But it's actually just another expression statement: a simple expression consisting of a single function call

printf("Hello, world!\n")

again followed by a semicolon.

like image 154
Steve Summit Avatar answered Oct 02 '22 09:10

Steve Summit