Why is 'int x = + "foo";' a type error but not a syntax error?

c++

Solution

Syntax doesn't involve types in the type system sense (ints and chars and pointers), only types in the syntactic sense of keywords, operators, expressions. In C++ syntax, `+` is a unary prefix operator that can precede an expression. `"foo"` is an expression. Therefore, `+"foo"` is a valid expression as far as the parser is concerned.

Your idea that the string constant decays into a pointer and `+` is a no-op on pointers is correct, and the following program even compiles and runs:

#include <iostream>

int main()
{
    const char *message = +"Hello!\n";
    std::cout << message;
}

... but that's irrelevant. What you're seeing is a type error, not a syntax error.

EDIT Perhaps even more convincing is the fact that you can overload unary `+`:

#include <iostream>

struct SomeType {
    const char *operator+() const
    {
        return "Hello, world!\n";
    }
};

int main()
{
    SomeType x;
    std::cout << +x;
}

Problem

All compilers I tried correctly reject the code ``` int main() { int x = "foo"; } ``` with a type error: `const char[4]` cannot be converted to `int`. Why is it that the same compilers (including Ideone.com) give the same error for ``` int main() { int x = + "foo"; } ``` instead of (as I would have thought) a syntax error becaus of the `+` sign? My first idea was that `const char[4]` decays to a pointer, which in turn is treated as an integral value so the `+` denotes "positive". Seems a little far-fetched though, and I would have expected to see `const char*` appear in the error message.

Original source

Related problems