-3

Hello this is the introductory programmer, well I guess I'm not even a programmer yet because I'm still learning basic grammars.

Here is my question. Can I initialize char type variable after declaration in c++? Or is it only possible to initialize char at the point of declaring?

KYUNGWAN RYOO
  • 11
  • 1
  • 2
  • you can declare a char var than initialize it after declaration and modify it. But better you initialize when declaring to no get junk on it. – Blood-HaZaRd Nov 30 '18 at 14:41
  • 1
    What kind of variable? Member variable? Global variable? Local variable? Static variable? How do you declare it? Is it extern? ... Sample code would be helpful. – Daniel Langr Nov 30 '18 at 14:43
  • 1
    I'm wondering is there could be a confusion between a char and a character array. – Matthieu Brucher Nov 30 '18 at 14:49

1 Answers1

0

You can only initialize a variable when you define it. For instance

char ch = 'a';

defines ch as a char and initializes it with the character literal 'a'. If you had

char ch;
//...
ch = 'a';

then you are no longer initializing ch but instead you are assigning to it. Until you reach ch = 'a'; ch has some unspecified value1 and using its value before you reach ch = 'a'; would be undefined behavior. Ideally you should always initialize a variable so it has a known state and since you can declare a variable at any point you can hold off on declaring the variable until you know what you are going to initialize it or when you are going to set it immediately. Example

//some code
// oh, I need to get a char from the user
std::cout << "Yo, user, give me a character: ";
char ch; // no initialization but it is okay as I set it immediately in the next line
cin >> ch; // now ch has a value
// more code

1: There are places will it will be initialized for you. For instance, if ch was declared in the global scope then it would be zero initialized for you

NathanOliver
  • 171,901
  • 28
  • 288
  • 402
  • Oh thank you for your sincere answer. But, if I would try what you called assigning to the variable, then my compiler would say like this: [Error] invalid conversion from 'const char*' to 'char' [-fpermissive]. Can you tell what mistake I have made with this? – KYUNGWAN RYOO Dec 03 '18 at 08:32
  • @KYUNGWANRYOO You.ll need to post a new question with the code that is giving you the problem. Sounds like you are dealing with c-strings and those are a different beast. – NathanOliver Dec 03 '18 at 13:38