array

Can somebody tell me what differences is between 2 below code.
The first code is OK.
But second Code has an error: error: variable-sized object 'b' may not be initialized variable-sized object 'b' may not be initialized.

int a=50;
char b[50]={0};
int a=50;
char b[a]={0};

Thanks.

But second Code has an error: error: variable-sized object 'b' may not be initialized variable-sized object 'b' may not be initialized.

Where are you trying to create a variable sized array? That is almost always a bad idea.

If you REALLY need to, the variable needs to be const.

I'm thinking its because declaring a variable doesn't make it an instance of the variable. As a matter of fact, no storage is allocated by the compiled code unless a declared variable is actually used in 'active' code somewhere (a function, or in setup() or loop() ). I believe that what is happening is (even though you are assigning a default value for 'a'), the compiler sees that as a placeholder.

int a=50; // compiler will create this variable later
char b[a]={0}; // so "a" is a place holder and the value cannot yet be used

One way it can be done up in the declaration area is to use a #define, like:

#define a 50

char b(a)={0};

And that's not a good way, but it is a way.

The best way to trick the compiler is:

const int a=50;
char b[a]={0};

Which should compile.

Your original code gives me a different error in the Arduino 1.6.4 IDE:
error: array bound is not an integer constant before ']' token
array bound is not an integer constant before ']' token

so using the 'const' modifier makes it happy.

Variable-sized arrays work fine, you just can't use an initializer:

int a = 50;
char b[a];
for (int i=0; i<a; i++) b[i] = 0;

I'm curious: I see code like:

for (int i=0; i<a; i++) 
   b[i] = 0;

quite often. I wonder which is more efficient; the code above, or:

   memset(b, 0, sizeof(b));

I would hope memset is the better approach, if it's needed at all.

memset is faster but if 'b' is an array of objects and not an array of simple integer type then the results could be wrong since the object constructors won't be called.

Isn't initialisation what constructors are designed for?

AWOL:
Isn't initialisation what constructors are designed for?

Yes, but if you use memset() you are casting the array to a character array and setting that character array to all zeroes.

I would hope memset is the better approach, if it's needed at all.

True for global data, but it might be useful for local arrays or integers or chars.