Expression vs Statement vs Expression statement in programming
Hello guys, I know it's a silly question but what is the difference between a statement, an expression and an expression statement in programming?
From what I understood (please confirm and add to it if required), an expression should always return a value, a statement may or may not return a value (what does this mean? can someone elaborate and give example pls). What about "expression statement"
14 Replies
you mean this?
the thing is am confused about how to differentiate a statement from an expression since a statement itself can return a value. if we have 5 + 3; this gives us 8, if we don't assign it to y, this is called an expression or statement
5 + 3;
standalone will not work in C# (safe to say C, C++)nah, I mean for example inside a console.writeline statement
A statement is something which does something, for instance
Console.WriteLine
writes to the console.
An expression is something which returns a value, for instance x + 1
returns the value contained within x
plus 1.
you can do that just tested it to be sure
key point
- The expression must evaluate to a value of a type that is compatible with the function’s parameter.
- The expression must not have syntax errors or invalid operations.
Statements - C#
Learn about statements in C# programming. See a list of statement types, and view code examples and additional resources.
Yep I see
the thing is, statements must do something, like we can't say x + 1 is a statement on its own because it doesn't do anything unless we assign it to some variable
yep
x + 1;
doesn't make sense because it doesn't "do anything"
However, when you call a method, that might do something, but it may also return a value! That is why we can call methods both as statements and as expressions, eg. we can call a method like int x = DoSomething() + 1;
but also as DoSomething();
. When we specifically use a method call as a statement, that is called an expression statement.ah yeah I see
yep, got it, thanks !!
np :meow_owo:
x + 1;
will return compile error
x++;
works but does nothing
very interesting
x++ is like x = x + 1;
okay it works like normal C :NotedHmm: