[SOLVED] Problem with void function

Hello everyone! I'm new here as I'm new to programming, right now I'm studying how to write my own functions. After a couple of exercise i tried writing a void function but i get the error " expected primary expression before 'a' "

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
#include <string>
using namespace std;

void box_string(string x)
    {
     int n = x.length();
     for(int i = 0; i < n + 2; i++){cout<<"-";}
     cout<<endl;
     cout<< "!" << x << "!" << endl;
     for(int i = 0; i < n + 2; i++){cout<<"-";}
     cout<<endl;
    }

int main()
{
    string a = "Hello";
    a = box_string(string a);

    return 0;
}


Any clue why the compiler complains?
Last edited on
The void function does not "return" any value. Therefore, it should be something like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>
#include <string>
using namespace std;

void box_string(string x)
{
    int n = x.length();
    for (int i = 0; i < n + 2; i++){ cout << "-"; }
    cout << endl;
    cout << "!" << x << "!" << endl;
    for (int i = 0; i < n + 2; i++){ cout << "-"; }
    cout << endl;
}

int main()
{
    string a = "Hello";
    //a = box_string(string a); // It doesn't return any value.
						  // The variable type "string" cannot
						  // accompany with the variable when
						  // you are calling the function.

    box_string(a); // Since it doesn't return a value.
			    // You are calling the function to execute.
    return 0;
}


This link has a better explanation on functions:
http://www.cplusplus.com/doc/tutorial/functions/
Last edited on
Hey and welcome =)

The point of void function is that they do not return anything.

a = box_string(string a);

Which means this is invalid, for three reasons actually.

1. "a" has no type (int, std::string, double, etc)

2. void doesnt return anything.

3. that's not exactly how you pass an argument.

It should look like this - box_string(a);

http://www.cplusplus.com/doc/tutorial/functions/
Last edited on
Oh dear! Of course! It doesn't return a value! I just need to create a string and then call the function with the string_name inside the parentheses! Thanks a lot both of you!
Topic archived. No new replies allowed.