Simplicity
Simplicity

Reputation: 48916

C++ - error: expected primary-expression before '<<' token

When I add this statment (the_pointer is of type int*)

<<"\nThe contents of the variable the_pointer is pointing at is : "<<*the_pointer;

The compiler returns the following error:

error: expected primary-expression before '<<' token

Why is that?

Thanks.

Upvotes: 2

Views: 26697

Answers (4)

TonyK
TonyK

Reputation: 17114

Judging by your comment to your question, you had something like this:

std::cout << x
          << y
          << z ;

This is all one statement, because there is no semi-colon statement terminator after x or y. But the next such line will fail, because of the semi-colon after z.

Upvotes: 5

ak.
ak.

Reputation: 3449

The following program compiles and runs fine:

#include <iostream>

int main(int argc, char *argv[]) {
    int val = 10;
    int *ptr_val = &val;
    std::cout << "pointer value: \n";
    std::cout << *ptr_val;
    return 0;
}

Upvotes: 0

tdammers
tdammers

Reputation: 20721

Because << is not a unary prefix operator, it needs two operands. When used for stream output, the left operand is an output stream, and the right operand is what you want to send to the stream. The result is a reference to the same stream, so you can append more << clauses to it. In any case, however, you need a left operand at all times.

Upvotes: 0

tenfour
tenfour

Reputation: 36896

<< is an operator which takes two arguments - left-hand and right-hand. You have only provided the right-hand side. Change your code to:

std::cout << "\nThe contents of the variable the_pointer is pointing at is : " << *the_pointer;

And make sure you #include <iostream> near the top of your source file so you can use std::cout.

Upvotes: 0

Related Questions