Reputation: 374
In c, the syntax of declaring a variable of a given type goes like this:
// <variable-type> <variable-name>
// for example:
int foo;
To declare a pointer, you use the asterisk(*), either behind the type, or in front of the variable-name.
int* bar;
int *foobar;
This pointer could also point not to a single element, but to an array of elements of the given datatype.
For example, an array of characters (a string):
char* oneString = "this is a string";
The alternate declaration(edit: although definitely not equivalent, as pointed out in the comments) of such a string then looks like the following:
//<variable-type> <variable-name>[<count>]
//example:
char anotherString[1024] = "this is another string";
In c# for comparison, you have it the other way around:
int[] intArray;
What were the considerations of effectively declaring an array at the variable-name, instead of its type?
(not intended as another question, only to provide means of comparing design-decisions)
What might have been the reasons for the people creating c#, to break with this rule, and move the array-declaration to the type itself?
Upvotes: 3
Views: 528
Reputation: 119867
The alternate declaration of such a string then looks like the following
It is a declaration of a different thing. It is not an alternative to the first declaration. In some contexts you can use them interchangeably, in other contexts you cannot.
In c# for comparison, you have it the other way around
Different languages are different.
What were the considerations of effectively declaring an array at the variable-name, instead of its type?
The design consideration was "declaration follows use". This means that if you are using a variable like this: a[i]
and the result is int
, you declare it like this: int a[N];
. If you use it like this *a
, you declare int *a
. If you need *a[i]
, declare int *a[N]
, and if you need (*a)[i]
, declare int (*a)[N]
.
What might have been the reasons for the people creating c#, to break with this rule
The designers of C# have decided that the "declaration follows use" principle is confusing and not needed in their language. You decide if they were right.
Upvotes: 8