In C/C++, what's the difference between the following two line code:
char *str1="hello";
char *str2={"hello"};
In C/C++, what's the difference between the following two line code:
char *str1="hello";
char *str2={"hello"};
Per the 2011 C standard, clause 6.7.9 Initialization, paragraph 11: “The initializer for a scalar shall be a single expression, optionally enclosed in braces…”
That is it. There is no semantic difference; the braces simply may be present or may be absent, with no change to the meaning.
Style only in this case. They both result in the same thing, and they're both bad form. You should have used const char * str1="hello";
.
See https://stackoverflow.com/a/3462768/153225.
The braces are redundant.
Generating assembler form 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();
}
There is no difference between an array and a "string", due a string is an array of characters.