On 8/8/2011 2:41 PM, Saqib Ali wrote:
>
> I'm on a Solaris 10 box.
> The compiler I'm using is: /opt/solstudio12.2/bin/CC
That doesn't really matter. You've broken several rules, and any
compiler worth the energy it takes to run it, should complain.
>
> Compiling the file shown below (myTest2.C) fails.
>
> % CC -I. -o myTest2 myTest2.C
> "myTest2.C", line 30: Error: "{" expected instead of "myFunc".
> "myTest2.C", line 33: Error: "{" expected instead of "myFunc".
> 2 Error(s) detected.
>
> Why is it an error to call myFunc() while declaring a variable?
It's not.
> How to get around it?
It depends on what you're trying to achieve.
>
> ----------------------------------------------------------------------------
> #include<iostream>
> #include<string>
>
>
>
> using namespace std;
>
>
> char* myFunc(string inString)
> {
> char outString[1024];
> int i;
> for (i = 0; i<= inString.size()-1; i++)
> outString[i] = inString[i];
> outString[i+1] = '\0';
> return outString;
You're returning a POINTER to a local array. As soon as the function
returns, the pointer that is returned becomes *invalid*. Don't code
like that.
> }
>
>
>
>
>
> extern "C" {
> }
>
> // This Works:
> static char myVariable1 [ ] = "MyString1" ;
This is explicitly allowed. The array of char of unknown size can be
initialized with a string *literal*.
>
> // This Breaks:
> static char myVariable2 [ ] = myFunc("MyString2") ; // Line #30
An array cannot be initialized from a pointer. Your function call is an
expression that yields a pointer to char. You could write
char* ptr = myFunc("MyString2");
static char myVariable2[] = ptr;
and you'd get the same error.
>
> // This Breaks:
> char myVariable5 [1024] = myFunc("MyString3"); // Line
> #33
Same problem. An attempt to initialize an array from a pointer.
> int main()
> {
> // This Works:
> string Z = myFunc("Gdkkn Vnqkc");
The class 'std::string' has a constructor that takes 'char const*'.
That's called "parameterized constructor" and is explicitly allowed.
What book on C++ are you reading that doesn't explain such basic stuff?
> cout<< "Z = "<< Z<< endl<< endl;
>
> }
V
--
I do not respond to top-posted replies, please don't ask
|