Thread: Defining char arrays as string literals

  1. #1
    Programming Ninja In-T...
    Join Date
    May 2009
    Posts
    827

    Question Defining char arrays as string literals

    Is it legal to do something like this:

    Code:
    char undo[5];
    
    int main {
     
     undo[] = "Undo"; 
    
    }
    ?

  2. #2
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    No. You can only use initializers when you declare the variable, not later.

    (Although, since we're in the C++ forum, you should have a reason for using char[] instead of string.)

  3. #3
    Programming Ninja In-T...
    Join Date
    May 2009
    Posts
    827
    Quote Originally Posted by tabstop View Post
    No. You can only use initializers when you declare the variable, not later.

    (Although, since we're in the C++ forum, you should have a reason for using char[] instead of string.)
    My question was more concerning if I could define a char array as a string literal, than anything else...
    And I do believe you can define a variable (though mine was actually a char array) after declaring it.

  4. #4
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,412
    Quote Originally Posted by Programmer_P
    And I do believe you can define a variable (though mine was actually a char array) after declaring it.
    That is true, but in this context tabstop meant define, not just declare.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  5. #5
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,057
    What you can do is one of these . . .
    Code:
    #include <cstring>
    char undo[5];
    int main() {
        std::strcpy(undo, "Undo");
        return 0;
    }
    Code:
    const char *undo;
    int main() {
        undo = "Undo";
        return 0;
    }
    By the way, you could always just try typing something into your favourite editor and seeing if it compiles . . . and if you're at a computer without a compiler (which happens to me sometimes), you no longer have an excuse!

    Dinkumware, Ltd. - Compleat Libraries Reference -- the Dinkumware online compiler
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

  6. #6
    Programming Ninja In-T...
    Join Date
    May 2009
    Posts
    827
    Quote Originally Posted by dwks View Post
    By the way, you could always just try typing something into your favourite editor and seeing if it compiles . . . and if you're at a computer without a compiler (which happens to me sometimes), you no longer have an excuse!

    Dinkumware, Ltd. - Compleat Libraries Reference -- the Dinkumware online compiler
    Hey, that's awesome! An online compiler!
    And my code actually compiled.

    I wrote this:

    Code:
    #include <iostream>
    using namespace std;
    
    char undo[5]; //declare char array for the purpose of storing the string "Undo"
    
    int main()
    	{
            char undo[] = "Undo"; //define char array as the string literal "Undo"
    	return 0;
    	}
    and then hit Compile, and it compiled successfully!

    Here are the results:

    Dinkum Exam? page results:

    Your code has been compiled with the Microsoft Visual Studio 2005 C++ compiler using
    the Dinkum C++ library from the Dinkum Compleat Libraries for VC++ package.

    This is the compiler output using the code above in a file named
    sourceFile.cpp:

    --------------------

    sourceFile.cpp

    --------------------

    size sourceFile.exe :
    2048t + 1536 .rdata + 512d = 4096 (1000)

    Code compiled successfully!
    The executable generated was 5 KB.

    Click on the 'Order On-Line' button to buy the library for immediate download.

    All rights reserved 2006 by Dinkumware, Ltd.
    Copyright (c) 1996-2006 by Dinkumware, Ltd.
    Dinkumware, Dinkum, Jcore, and Proofer are registered trademarks of Dinkumware, Ltd.
    So I take it that code is legal after all?

    Now what if I wanted to output the char array string?

    Could I do something like this:

    Code:
    #include <iostream>
    using namespace std;
    
    char undo[5]; //declare char array for the purpose of storing the string "Undo"
    
    int main()
    	{
            char undo[] = "Undo"; //define char array as the string literal "Undo"
            cout<< undo[] <<endl;
    	return 0;
    	}
    Last edited by Programmer_P; 06-05-2009 at 10:36 PM.

  7. #7
    Programming Ninja In-T...
    Join Date
    May 2009
    Posts
    827
    Ok, so that didn't work, so I changed it to

    Code:
    #include <iostream>
    using namespace std;
    
    char undo[5]; //declare char array for the purpose of storing the string "Undo"
    
    int main()
    	{
            char undo[] = "Undo"; //define char array as the string literal "Undo"
            cout<< undo <<endl;
    	return 0;
    	}
    without the [], and it compiled!
    Only trouble is I'm not sure what it outputted. Hopefully it was

    Undo

  8. #8
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,412
    Quote Originally Posted by Programmer_P
    So I take it that code is legal after all?
    Notice that what you compiled and what you originally posted are different. The code that you compiled defines a global array, of 5 chars, named undo, and also defines a local array named undo initialised with "Undo". As such, the local variable hides the global variable of the same name.

    Actually, since the global array is unnecessary, you should just remove it.

    Quote Originally Posted by Programmer_P
    Now what if I wanted to output the char array string?
    You could write:
    Code:
    cout << undo << endl;
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  9. #9
    Programming Ninja In-T...
    Join Date
    May 2009
    Posts
    827
    Quote Originally Posted by laserlight View Post
    Notice that what you compiled and what you originally posted are different. The code that you compiled defines a global array, of 5 chars, named undo, and also defines a local array named undo initialised with "Undo". As such, the local variable hides the global variable of the same name.

    Actually, since the global array is unnecessary, you should just remove it.


    You could write:
    Code:
    cout << undo << endl;
    Ahh...I was wondering if putting the "char" keyword in int main before the array line made any difference or not. What kind of effect would it have if I had that same array declared in a class instead of as a global array, and then defined it in a function (though not int main)?

    For example:

    Code:
    class edit_menu_options_class : public edit_menu_class 
     {
        public:
          edit_menu_options_class(); //this will be the constructor for the class
          ~edit_menu_options_class(); //this will be the destructor for the class
    
        protected:
         char undo[5]; 
         
        private:
          void edit_menu_options_mod_function(void); 
          void edit_menu_options_function(); //declare function for manipulating the options in 
    
    }; //END edit_menu_options_class
    
      edit_menu_options_class::edit_menu_options_class(edit_menu_options_mod_function(void))
        { //BEGIN brace for edit_menu_options_mod_function
    
          undo[] = "Undo"; 
    
    int main {
      
      cout<< undo <<endl;
      return 0;
    }

  10. #10
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,412
    Quote Originally Posted by Programmer_P
    What kind of effect would it have if I had that same array declared in a class instead of as a global array, and then defined it in a function (though not int main)?
    You would get a compile error

    The member array would be defined when an object of the class is defined, hence you would not be defining it in the member function, thus that initializer syntax would no longer work.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  11. #11
    Programming Ninja In-T...
    Join Date
    May 2009
    Posts
    827
    Quote Originally Posted by laserlight View Post
    You would get a compile error

    The member array would be defined when an object of the class is defined, hence you would not be defining it in the member function, thus that initializer syntax would no longer work.
    Damn! That sucks...
    I was hoping to avoid having to define all the members of my class in int main...
    I'm trying to have every part of my program (or close to it...) in its own file, and call it from inside the int main function in main.cpp. WHY is it not allowed to define a member of a class inside a member function?

  12. #12
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,412
    Quote Originally Posted by Programmer_P
    I was hoping to avoid having to define all the members of my class in int main...
    In this context, what do you mean by "define"? When you define an object, you define its member variables.

    Quote Originally Posted by Programmer_P
    WHY is it not allowed to define a member of a class inside a member function?
    As in you want to create a new member variable at run time? If you accept that you cannot directly do that due to the rules of C++, then the reason is that the member variables are defined when the object is instantiated. By the time the member function is called, they already exist.

    What I would do is examine if edit_menu_options_class really should have such a member variable. Maybe it should be a local variable. If it should be a member variable, then change it to be a std::string instead, then use assignment in the member function. Or maybe you should be initialising it in a constructor.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  13. #13
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    Presumably you would want to define each of your objects separately (one object would be "undo", one object might be "Redo", etc.), so your constructor would need to be able to handle different strings.

    I think the biggest issues here are your belief that char arrays should be used in C++ in any but the most extreme circumstances and your lack of use of strcpy to assign C-style strings (i.e., char arrays). Why not use a string? Why not use strcpy?

  14. #14
    Programming Ninja In-T...
    Join Date
    May 2009
    Posts
    827
    Quote Originally Posted by laserlight View Post
    In this context, what do you mean by "define"? When you define an object, you define its member variables.
    Exactly! And can't you only define (and/or declare) objects inside int main (which would exist in the main source code file)?
    The whole point I'm getting at here is I want to define my member variables inside the same file as the class, and so in this particular case, the same file which will store "edit_menu_options_class" which will be separate from main.cpp.
    As in you want to create a new member variable at run time? If you accept that you cannot directly do that due to the rules of C++, then the reason is that the member variables are defined when the object is instantiated. By the time the member function is called, they already exist.
    No. As in "I want to define a member of a class inside a member function, and can't!".
    I understand what you're saying and all, I just think it sucks that C++ doesn't allow this...
    What I would do is examine if edit_menu_options_class really should have such a member variable. Maybe it should be a local variable. If it should be a member variable, then change it to be a std::string instead, then use assignment in the member function. Or maybe you should be initialising it in a constructor.
    Ok, so would something like this work?

    Code:
    class edit_menu_options_class : public edit_menu_class
    
      {
    
        public:
         edit_menu_options_class(); //this will be the constructor
         ~edit_menu_options_class(); //this will be the destructor
       protected:
         std::string undo;
       private:
       //add private members here
    
      }; //end class
    
    edit_menu_options_class::edit_menu_options_class() {
      undo = "Undo";
    }
    
    int main {
      cout<< undo <<;
      return 0;
    }
    Nah, there's probably about a billion syntax errors in it...
    Last edited by Programmer_P; 06-05-2009 at 11:52 PM.

  15. #15
    Programming Ninja In-T...
    Join Date
    May 2009
    Posts
    827

    Talking

    Quote Originally Posted by tabstop View Post
    Presumably you would want to define each of your objects separately (one object would be "undo", one object might be "Redo", etc.), so your constructor would need to be able to handle different strings.

    I think the biggest issues here are your belief that char arrays should be used in C++ in any but the most extreme circumstances and your lack of use of strcpy to assign C-style strings (i.e., char arrays). Why not use a string? Why not use strcpy?
    Because I'm lazy, and that stuff is complicated!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. String Manipulation problems -_-
    By Astra in forum C Programming
    Replies: 5
    Last Post: 12-13-2006, 05:48 PM
  2. newbie needs help with code
    By compudude86 in forum C Programming
    Replies: 6
    Last Post: 07-23-2006, 08:54 PM
  3. Replies: 4
    Last Post: 03-03-2006, 02:11 AM
  4. Linked List Help
    By CJ7Mudrover in forum C Programming
    Replies: 9
    Last Post: 03-10-2004, 10:33 PM
  5. lvp string...
    By Magma in forum C++ Programming
    Replies: 4
    Last Post: 02-27-2003, 12:03 AM