9

I am refreshing my self on C++ (have not did it since school) and I wrote a simple program just to mess around. My problem is when I compile the program it chokes stating "error: expected initializer before 'stringThing'" is there a reason why this is doing this? I know this may be a noob question so I checked stackoverflow and could not find any relevant questions that gave me a answer.

*I am using GNU GCC compiler

Code:

#include <iostream>

using namespace std;

void string stringThing (string shiftdir, string &teststring)
    {
        if (shiftdir == "right")
        {
           teststring = teststring >> " " >> "Bit Shifted right";
        }
        else
        {
           teststring = teststring << " " << "Bit Shifted left";
        }
    }
int main()
{

    string test;

    cout << stringThing("right", "I have done a ") << endl;

    return 0;
}
WorkerBee
  • 683
  • 3
  • 11
  • 22
  • 1
    This is the sort of question that is answered not through random five-minute Googling, but by [learning C++ from a good book](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). This incorrect syntax is not taught in any C++ book. – Lightness Races in Orbit Jan 14 '13 at 16:00
  • For anyone who may have simply forgotten the `=` sign as an assignment operator before the function call, see my Q&A here: [error: expected initializer before ‘myFunction’ in C or C++](https://stackoverflow.com/q/73504318/4561887) – Gabriel Staples Aug 26 '22 at 16:58

2 Answers2

5

The return type for stringThing must be either void or string, not both. You also must include <string>, if you want to use string.

Since you want to output the return value of stringThing() in main, I guess it should be

std::string stringThing (std::string shiftdir, const std::string &teststring)

But then, you must also return a string from your function

if (shiftdir == "right")
    return teststring + " " + "Bit Shifted right";
else
    return teststring + " " + "Bit Shifted left";

for example.

Your parameter std::string &teststring won't work with your const char* argument. So either declare it as a copy by value string only, or better const string&.

Olaf Dietsche
  • 72,253
  • 8
  • 102
  • 198
4

Return type is … funky

What is:

void string stringThing (string shiftdir, string &teststring)

?

Get rid of the first string. Your function returns nothing.

So, simply:

void stringThing(string shiftdir, string &teststring)

Inclusion missing

You will also need to #include <string> — in some scenarios you may get "lucky" and have it implicitly included by <iostream>, but don't rely on it.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
  • 1
    Also, `#include ` would be a good thing to do, regardless of whether it's included in ``. – chris Jan 14 '13 at 16:00