Fundamentals

Maybe it is the way we learnt programming by patterns – “Do this and that will happen” or “this is how it is done”. Maybe we don’t stop to think how things work at more fundamental level.

Here is a piece of code which works in some languages (C, C++, JavaScript) but won’t work in others (Java, C#)

C/C++ allows a statement like 1, 2, 3;
/*
   Works in C/C++
*/
int main()
{
    1, 2, 3;  // Why does this work? What does it mean?
}

Java and C# don't allow 1, 2, 3
/*
   Java (and C#) don't allow
*/
class MyClass {
    static void main(String[] args) {
        1, 2, 3; // Gives an error.. Why?
}

Why do you think this is? Is there a fundamental reason these languages differ? Why did Java disallow this? If you know why, write it in comments below

6 thoughts on “Fundamentals

      1. I thought, you would want me to wait for others to answer! 🙂

        Java, comma is not really an operator but a separator. Because ‘for’ expressions allow comma-separated initializations and updates, many seem to believe that ‘comma’ is being used as an expression. That’s not correct.

        Without going into the details, it is important to understand how an Expression and a Statement are formed in Java, according to the Java’s grammar notations. These help us infer why the Java Compiler complains that this line is *not a statement*, even though we have put a semicolon at the end, dutifully!

        In case of ‘C’, it is a complete expression. That statements evaluates to a value, which by the way, is not being assigned to any variable, so that the value can be used for further computation. The Compilers perhaps knows that it is an wasteful computation, but lets it go because we are not breaking any rules.

        Like

  1. Absolutely correct! However, the comma was the red herring here.

    In C/C++
    // Valid statement as all expressions are statements too
    1;

    In Java/C#
    // Error as non void functions, assignments, increment, decrement are statements, but not value
    1;

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s