cexpressionlanguage-lawyervariable-assignment

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;

Solution

  • 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.