6

Normally in C++, character arrays are initialized in the following way,

char example[5]="cat";

What if you initialize it with "" (just a double quotes without spaces)?
What will be the elements in the character array after initialization?

Undo
  • 25,519
  • 37
  • 106
  • 129
chinthana
  • 183
  • 1
  • 3
  • 9
  • 2
    @trojanfoe no, that will just tell him the first character is `'\0'`. What about the rest? – Luchian Grigore Jul 22 '13 at 14:28
  • 1
    @LuchianGrigore The debugger isn't limited to showing the first character. – trojanfoe Jul 22 '13 at 14:29
  • 19
    @trojanfoe: A lot of C++ behaviour is undefined or implementation defined; trying things on one platform and compiler does not necessarily tell you what the behaviour will be on other platforms. Therefore, the "try it and see" approach is not, in general, a reliable method. – John Bartholomew Jul 22 '13 at 14:30
  • @trojanfoe the debugger can put any characters after the first, that doesn't make it a rule. When talking about C++, it's not as easy as saying "try it and you'll see" all the time. This is one of those situations where a debugger can do more harm than good, because it can lie to you - you can't make any assumptions based on it. – Luchian Grigore Jul 22 '13 at 14:31
  • @JohnBartholomew Is this *undefined behaviour* though? – trojanfoe Jul 22 '13 at 14:31
  • @trojanfoe it doesn't matter. What if it was? – Luchian Grigore Jul 22 '13 at 14:32
  • 1
    @trojanfoe: If I knew that I would post an answer. But, importantly, *you can't tell* whether it's well defined just by compiling it and examining the program's behaviour. – John Bartholomew Jul 22 '13 at 14:34
  • I agree it's not good to encourage people just to go with what the debugger reports. – Neil Kirk Jul 22 '13 at 14:34
  • Well it really depends on how you look at it. The OP may not be interested in what all compilers are *supposed to do* then debugging it and finding out is perfectly valid. – trojanfoe Jul 22 '13 at 14:38
  • @trojanfoe no it's not. If the behavior was that the rest of the characters are uninitialized, and a compiler decides to write `0` instead, looking with a debugger can lead to the false assumption that the whole array is initialized to `0`. Of course, in this case it doesn't apply, but it's a perfectly valid question. – Luchian Grigore Jul 22 '13 at 14:46
  • @LuchianGrigore That's just failing to use the debugger properly; you can use watchpoints to determine if zero is being written over zero. – trojanfoe Jul 22 '13 at 14:54
  • @trojanfoe no, the compiler can choose to set the values to 0 to help with debugging. The point is you can't draw any conclusions. In MSVS if I write `int x;`, in debug mode it will set `x` to `0`. I can't draw any conclusions from there, because `x` is theoretically uninitialized, and on a release build the debugger will show a garbage value. – Luchian Grigore Jul 22 '13 at 14:57
  • I think that is a bit heavy for a beginner to be expected to do. Make it easy for them to learn, not harder. – Neil Kirk Jul 22 '13 at 14:57
  • @NeilKirk However you appear to have used a similar approach when you answered the question. I don't understand your objection given the statement "After an experiment, it appears the remaining characters are set to 0". – trojanfoe Jul 22 '13 at 14:59
  • I am not perfect. I have since changed my mind. – Neil Kirk Jul 22 '13 at 15:01

4 Answers4

12

The declaration

char    temp[3] = "";

is same as

char    temp[3] = {0};
                  // `\0` ascii value is 0

remember remaining elements of half initialized array initialized with 0.

Point :char temp[3] = "" is easy to type(means writing), so its preferable.

Look even compare it with this declaration char temp[3] = {'\0'}; (it need more chars to type) Whereas in char temp[3] = ""; is simple (even no type mismatch - int/char).

Grijesh Chauhan
  • 57,103
  • 20
  • 141
  • 208
  • initialized with 0 in the sense ?? it's a character array. – chinthana Jul 22 '13 at 14:37
  • @user2607152 acii value of `\0` nul char is `0` zero, Got it? and because acsii-value to char are compatible we can assign chart to `0` – Grijesh Chauhan Jul 22 '13 at 14:38
  • I actually ran into a VP of development who did not know this about C and called it "too complicated" when I used it. Wanted me to leave the array uninitialized and use memset instead. He wanted everything to be written in C because that's what he "knew". – Edward Strange Jul 22 '13 at 14:40
  • 3
    It's even the same as `char temp[3] = {};` – Benjamin Lindley Jul 22 '13 at 14:45
  • @BenjaminLindley true **?** I didn't try let me try lots of thanks to inform me this. – Grijesh Chauhan Jul 22 '13 at 14:45
  • @user2607152 Please read Mr. Benjamin Lindley's comment to my answer, very interesting. – Grijesh Chauhan Jul 22 '13 at 14:51
  • @BenjaminLindley awesome its working, even in C!!!!! I am super surprise that even `char temp[] = {};` compiled success fully..please give me a information how doesit work a link to read. Thanks very much. – Grijesh Chauhan Jul 22 '13 at 14:54
  • 2
    = {} sets all elements to a default value. For integers, it is 0. – Neil Kirk Jul 22 '13 at 14:56
  • @NeilKirk Thanks! that I got at first chance but how this works `char temp[] = {};` – Grijesh Chauhan Jul 22 '13 at 14:58
  • @GrijeshChauhan: That doesn't work, it needs a size. If it does work for you, then it's a non standard extension, probably of gcc. Try `-pedantic-errors` for standard enforcement. – Benjamin Lindley Jul 22 '13 at 15:00
  • I didn't notice the size is missing. I doubt that will compile. If it does, it's a useless construct. – Neil Kirk Jul 22 '13 at 15:02
  • @BenjaminLindley I compiled with `gcc 4.4` not error, I didn't use this flag but Thanks again for this! – Grijesh Chauhan Jul 22 '13 at 15:03
  • @NeilKirk thanks Neil for your response, yes I already found a bug in my compiler `gcc 4.4`, I will try with new one, but yes its working with `gcc 4.5`. – Grijesh Chauhan Jul 22 '13 at 15:07
  • @BenjaminLindley Please check the link: Why [int `array[] = {}`;](http://codepad.org/Q3RNPv32) is working **?** I do not understand it **?** – Grijesh Chauhan Jul 24 '13 at 08:38
  • 1
    @GrijeshChauhan: You compiled that as C. I don't know C as well as C++, especially when it comes to arrays, where there are some differences, especially since C99. But if you try that in C++, it is, as I said, definitely not standard. I don't know anything about GCC's extensions. I always compile with `-pedantic-errors` to enforce the standard. Maybe read [this](http://gcc.gnu.org/onlinedocs/gcc/Zero-Length.html). Though I'm not sure if that's what's being used here, because it says they can only be used as the last member of a struct. – Benjamin Lindley Jul 24 '13 at 14:56
  • @BenjaminLindley Thanks Benjamin! as much I know C I have impression that that compiler is buggy, but it was working in my machine to that the reason..Thanks for the Link too! – Grijesh Chauhan Jul 24 '13 at 16:21
  • 1
    @GrijeshChauhan: It compiled even when you added the `-pedantic-errors` flag? – Benjamin Lindley Jul 24 '13 at 16:32
  • @BenjaminLindley Ahaa, got an error: with `-pendatic -error` --zero or negative size array 'a'. Thanks! – Grijesh Chauhan Jul 24 '13 at 16:40
  • In C, `char temp[3] = {};` is invalid; some compilers may support it as an extension. And the `char temp[3] = {'0'};` in the answer is not equivalent to `char temp[3] = "";`. `'0'` is the digit zero; you want `'\0'`, the null character. – Keith Thompson Aug 08 '13 at 15:38
  • @KeithThompson Thanks Keith! it was typo, now corrected. But did you notice [`int array[] = {}`](http://codepad.org/Q3RNPv32) also compiles without `-pedantic-errors`! – Grijesh Chauhan Aug 08 '13 at 18:28
  • @GrijeshChauhan: `int array[] = {};` is invalid according to the ISO C standard. I'm not surprised that it compiles with some compilers with certain options, but it's not portable. – Keith Thompson Aug 08 '13 at 18:38
  • @KeithThompson Yes I think It's a GCC compiler extension. But indeed a bad design that seems uselessly! – Grijesh Chauhan Aug 08 '13 at 18:48
  • How so? `some_type some_object = {}` initializes all elements to zero; it's like `{ 0 }` but with (IMHO) a cleaner syntax. And if you use `-pedantic`, gcc does warn about it: "warning: ISO C forbids empty initializer braces". – Keith Thompson Aug 08 '13 at 18:55
  • @KeithThompson One more doubt here: Is `char str[7] = "grijesh";` (`"grijesh"` consists of `8 chars`, `str[] is 7 size` )is valid or Undefined behavior **?** It doesn't give a warning/or error even with `gcc -Wall -pedantic` Whereas if I defined like `char name[7] = {'g', 'r', 'i', 'j', 'e', 's', 'h', '\0'};` it causes warning `excess elements in array initializer.` – Grijesh Chauhan Aug 29 '13 at 16:10
  • 1
    @GrijeshChauhan: `char str[7] = "grijesh";` is a special case in C; it gives you an array that doesn't contain a null-terminated string. C++ doesn't have that special case, and a C++ compiler should reject it. You should usually let the compiler count the characters: `char str[] = "grijesh";` (computers are really really good at counting things so you don't have to!). Though you can specify the length if you want to leave extra space: `char str[80] = "grijesh";` – Keith Thompson Aug 31 '13 at 22:49
9

It's a 3-character array initialized to three null characters.

EDIT (after comments below):

From K&R:

If there are fewer initializers for an array than the number specified, the missing elements will be zero for external, static, and automatic variables.

...

Character arrays are a special case of initialization; a string may be used instead of the braces and commas notation:

char pattern[] = "ould";

is a shorthand for the longer but equivalent

char pattern[] = { 'o', 'u', 'l', 'd', '\0' };

From a draft copy of the C++ standard, section 8.5.2, Character arrays:

"1. A char array (whether plain char, signed char, or unsigned char), char16_t array, char32_t array, or wchar_t array can be initialized by a narrow character literal, char16_t string literal, char32_t string literal, or wide string literal, respectively, or by an appropriately-typed string literal enclosed in braces. Successive characters of the value of the string literal initialize the elements of the array. [Example:

char msg[] = "Syntax error on line %s\n";

shows a character array whose members are initialized with a string-literal. Note that because ’\n’ is a single character and because a trailing ’\0’ is appended, sizeof(msg) is 25. — end example ]

...

"3. If there are fewer initializers than there are array elements, each element not explicitly initialized shall be zero-initialized (8.5)."

Andy Thomas
  • 84,978
  • 11
  • 107
  • 151
  • Is it three null character or is just the first one null? EDIT: Just tested it, youre correct – dchhetri Jul 22 '13 at 14:41
  • 5
    It's all of them. "If the initializer supplies too few elements, 0 is assumed for the remaining array elements." [Stroustrup, "The C++ Programming Language"] Also, be wary about determining C++ behavior by testing -- not only is there variant behavior among compilers, but one possible set of uninitialized data is all zeros. – Andy Thomas Jul 22 '13 at 14:47
  • @AndyThomas: Does that really apply to the string form or just the brace initializer form? I've always been under the impression that `temp[3] = "";` initializes only the first char, while `temp[3] = {0};` initializes all of them. – Adrian McCarthy Aug 07 '13 at 23:29
  • You get my upvote for pointing me where in the standard it says remaining elements are zero-initialized. I would not have expected that. – moswald Aug 08 '13 at 18:57
  • +1. Thanks for digging up the references to the equivalence between string and brace initialization. – Adrian McCarthy Aug 08 '13 at 21:24
2

A blank string. The first char will be the null terminator. After an experiment, it appears the remaining characters are set to 0 (which is also null terminator).

Neil Kirk
  • 21,327
  • 9
  • 53
  • 91
1

You are setting the first element to be a null termination character. The other elements gain partial initialisation to zero: C and C++ : Partial initialization of automatic structure

Community
  • 1
  • 1
TheDarkKnight
  • 27,181
  • 6
  • 55
  • 85
  • If someone is going to mark down an answer, they could at least have the decency to explain why! – TheDarkKnight Jul 22 '13 at 14:35
  • @harper, please explain why? Here's another reference: http://stackoverflow.com/questions/11780809/does-a-string-literal-count-as-a-partial-initializer-and-zero-initialize – TheDarkKnight Jul 22 '13 at 14:51
  • It is an array and not a structure. – Neil Kirk Jul 22 '13 at 14:54
  • @NeilKirk, I get your point, but the functionality is the same. See "Initialisation and Strings" here:- http://poeticcoding.com/main/c-programing/c-initialization-of-variables/ – TheDarkKnight Jul 22 '13 at 14:57
  • When you first wrote the answer, you said the other elements are not initialized. I didn't notice you have edited it. – Neil Kirk Jul 22 '13 at 15:00
  • @NeilKirk, no problem. I was trying to work out if I had a lack of understanding. Thanks for clarifying. – TheDarkKnight Jul 22 '13 at 15:03