1

I'm an absolute beginner to coding and to the world of c++. Have started reading a book named c++ primer and I encountered in one of the exercises a question that asks "Is this code legal?". I'm personally clueless about what this means or refers to as a beginner. Please guide a humble rookie in need!

2 Answers2

3

"Legal" colloquially means "well formed" and "not undefined" in this context.

Let's start with an analogy. The English language has rules. If I write to you in English: "äöldksfg", you wouldn't understand me, because that isn't a well formed word. If I wrote instead "if if if if if if", you would understand every word, but it still wouldn't be a well formed sentence. If I wrote "The treehorse hums with blasphemy", you would recognise the sentence structure as it is well formed, but it still probably makes little sense to you.

The C++ language - like the English language - has rules. The rules of programming languages are much stricter than human languages. The rules of the C++ language are written in the C++ standard document. As a document filled with rules, it is similar to a book of laws. Conforming to the book of laws makes your actions legal, and following the analogy, conforming to the rules of the C++ language makes your program "legal" as well.

eerorika
  • 232,697
  • 12
  • 197
  • 326
1

The rules for writing C++ code is described in a standard (See Where do I find the current C or C++ standard documents?)

If a piece of code complies to every single rule of the standard, it's legal code.

The first step is that the code must comply to the language syntax described by the standard. For instance:

int x = +/-;
int x =

are examples of illegal statements, i.e. illegal syntax. Your compiler will find such errors for you.

But it's much more complicated than that. The fact is that you can write code that complies to the language syntax but still is illegal.

A simple example:

int* x;

void foo(void)
{
    int n = 42;
    x = &n;
}

void bar(void)
{
    foo();
    printf("%d\n", *x);  // Illegal - using pointer to "dead" object
}

When you dig into C++ you'll find that there are so many ways to write code with legal syntax but illegal/undefined behavior.

Support Ukraine
  • 42,271
  • 4
  • 38
  • 63
  • Hm... I wouldn't have termed undefined behaviour as illegal. I would think of, for example, non portable code being more illegal, at least to the Standard's eyes, than UB code. – rturrado Sep 07 '21 at 12:14
  • @rturrado nah... non portable code is **not** illegal - it's just restricted to specific systems. – Support Ukraine Sep 07 '21 at 17:36
  • @rturrado but code with undefined behavior are illegal from standard point of view. Anything is allowed to happen... – Support Ukraine Sep 07 '21 at 17:50