What is the difference between hello and hello?

In C / C ++, what's the difference between the following two lines:

char *str1="hello"; char *str2={"hello"}; 
+7
source share
4 answers

According to C standard 2011, clause 6.7.9 Initialization, clause 11: β€œThe initializer for a scalar must be a single expression, not necessarily enclosed in curly braces ...”

That's all. There is no semantic difference; curly braces may simply be present or may be absent, without changing the value.

+10
source

Style only in this case. Both of them lead to the same, and they are both bad. You should have used const char * str1="hello"; .

+6
source

See https://stackoverflow.com/a/3188268

Brackets are redundant.

Generating assembler from the following code with "gcc -S" confirms that they generate exactly the same thing (with a slightly different constant in each case):

 #include <iostream> using namespace std; void test1() { const char *str1="hello1"; cout << str1 << endl; } void test2() { const char *str2={"hello2"}; cout << str2 << endl; } int main() { test1(); test2(); } 
+2
source

There is no difference between an array and a string, since a string is an array of characters.

-one
source

All Articles