1

I have following statement and it compiles:

static unsigned char CMD[5] = {0x10,0x03,0x04,0x05,0x06};

int Class::functionA(int *buflen)
{
    ...
    int length = sizeof(CMD); + *buflen; // compiler should cry! why not?
    ...
}

Why I get no compiler error?

leon22
  • 5,280
  • 19
  • 62
  • 100
  • 2
    What compiler? Do you compile with warnings on? When I compile with `g++ -Wall -Wextra -pedantic` I get "warning: statement has no effect", and `clang++ -Wall -Wextra -pedantic` gives "warning: expression result unused". – R. Martinho Fernandes Feb 07 '12 at 10:23

3 Answers3

8
+ *buflen;

Is a valid application of the unary + operator on an int&, it's basically a noop. It's the same as if you wrote this:

int i = 5;
+i; // noop

See here for what the unary operator+ actually does to integers, and here what you can practically do with it.

Community
  • 1
  • 1
Xeo
  • 129,499
  • 52
  • 291
  • 397
  • 1
    "it's basically a noop" - in some implementations it's equivalent to `if (!buflen) kill(getpid(), SIGSEGV);` or what-have-you ;-). But that might depend entirely on optimization options, and I do agree that all being well it does nothing. – Steve Jessop Feb 07 '12 at 10:48
  • @Steve: Uh, yeah, assuming that `buflen` actually points to something valid. :) – Xeo Feb 07 '12 at 10:54
4

Because it isn't wrong, just a statement with no effect.

If you compile (gcc/g++) with the flag -Wall you'll see.

Bruno Soares
  • 756
  • 5
  • 6
4

I guess from this Question's title "After semicolon another command and it compiles" that you think that there can only be one command/statement per line?

As you noticed, this is false. C++ and C are free-form languages (which means that you can arrange the symbols in any way you see fit). The semicolon is just a statement terminator.

You may write foo();bar(); or

foo();
bar();

Both (and more) arrangements are totally fine. By the way, that's a feature, not a bug. Some languages (Python, early Fortran) don't have that property.

As others have correctly pointed out, your specific statement is a no-op, a statement without any effect. Some compilers might warn you about that - but no compiler will warn you about multiple statements on one line.

rwos
  • 1,751
  • 1
  • 15
  • 18
  • 1
    Python allows multiple statements on the same line. What Python restricts is where you can break a single statement into multiple lines. – James Kanze Feb 07 '12 at 11:41
  • Yeah, I know that. In this case the problem was the + operator (see answer from Xeo)! – leon22 Feb 07 '12 at 12:05
  • @JamesKanze: Yes, that's correct. I meant it more like "Python is not a free-form language". But I can see that this specific "multiple statements on one line" case here is not a good example. – rwos Feb 07 '12 at 12:32