PresidentRFresh
PresidentRFresh

Reputation: 93

Returning a character string from a function.... restrictions?

I was wondeirng I have this particular parcel of code

char* usage()
     {
         static char errors[] = {"Sorry Invalid Option entered\nPlease Enter an appropriate option"};        
         return errors;
     }

I've called the function properly and it does what I want it to. However as Soon as I do this...I get a plethora of errors.

char* usage()
     {
         static char errors[] = {"Sorry Invalid Option entered\n
                                 Please Enter an appropriate option"};        
         return errors;
     }

All I did is put the second line one row below I get errors. Now, All i'm wondering is what is the difference between the two? I seemingly have the same argument entered into both character arrays. Is it due to the fact I did not malloc space for the array?

Upvotes: 0

Views: 158

Answers (2)

Daniel Frey
Daniel Frey

Reputation: 56863

C and C++ do not support multi-line literals that way, but you can use this:

char* usage()
{
     static char errors[] = {"Sorry Invalid Option entered\n"
                             "Please Enter an appropriate option"};        
     return errors;
}

note the additional quotes!

Upvotes: 9

pmg
pmg

Reputation: 108968

In C (I don't know about C++) you can write strings in several lines by using the fact that quotes concatenate the strings (this concatenation is done by the preprocessor)

char test[] = "one " "two" " " "<= that's a space :)" "\n"
              "three and four\n"
              "five etc and so on\n"
              "\n"
              "for ever and ever ...\n";

Note: no semicolons except on the last line.

Upvotes: 5

Related Questions