4

I'm little confused. What is the logically difference between these codes?

#include <iostream>
using namespace std;
int main(){
    char a[5]="ABCD"; // this
    cout << a;
    return 0;
}

Second is

char a[5]={"ABCD"}; // this

Third is

char a[5]={'A','B','C','D'}; // this
Asif Mushtaq
  • 3,658
  • 4
  • 44
  • 80

2 Answers2

6
char a[5]={"ABCD"};
char a[5]={'A','B','C','D','\0'};

In both cases, the array of characters a is declared with a size of 5 elements of type char: the 4 characters that compose the word "ABCD", plus a final null character ('\0'), which specifies the end of the sequence and that, in the second case, when using double quotes (") it is appended automatically.Attention adding null character separating via commas. A series of characters enclosed in double quotes ("") is called a string constant. The C compiler can automatically add a null character '\0' at the end of a string constant to indicate the end of the string.

Source:This link can help you better

NewCoder
  • 183
  • 1
  • 14
0

The first two are assignment of a char[5] source to a char[5] array with different syntax only. (the 5 being the four letters plus a null terminator)

The last one will also do the same, but it doesn't explicitly specify a null terminator. Since you are assigning to a char[5], the last one will still zero-fill the remaining space, effectively adding a null terminator and acting the same, but the last one will not throw a compiler error if you assign to a char[4]; it will just leave you with an unterminated array of characters.

mukunda
  • 2,908
  • 15
  • 21
  • why third one is not adding null char automatically? or why the first 2 methods adding null automatically? – Asif Mushtaq Jun 04 '15 at 17:58
  • @AsifMushtaq This answer says that the third one does add the null char - it's not right to ask why it doesn't! – anatolyg Jun 04 '15 at 18:07
  • @anatolyg I just asked that, why compiler not adding null char automatically? char a[5]={'A','B','C','D','\0'}; any logic? – Asif Mushtaq Jun 04 '15 at 18:21
  • "Why does the sun not shine?" - incorrect question: the sun does shine. "Why does the compiler not add 0 in `char a[5]={'A','B','C','D'}`?" - incorrect question: the compiler does add it. Sorry for the metaphor; I hope it's clear now. – anatolyg Jun 04 '15 at 18:26
  • It's just that the null terminator is not actually coming from a string literal in the third case, it's only there because there is extra space in the buffer that is being filled with zero. – mukunda Jun 04 '15 at 19:15