سؤال

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?

هل كانت مفيدة؟

المحلول

+ *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.

نصائح أخرى

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

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

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.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top