Reputation: 8051
Consider:
int *arr = new int[10];
I have seen three ways of writing the line of code for freeing arr
: delete[] arr
, delete [] arr
and delete []arr
. First, since delete[]
is the name of the operator, how come it is legal to introduce a space between delete
and the square brackets? Second, what is the logic behind the various ways and which way should be preferred?
Upvotes: 0
Views: 139
Reputation: 141930
how come it is legal to introduce a space between delete and the square brackets?
Because the language grammar allows it.
Usually in most context whitespaces (tabs, newline, spaces) are ignored. Whitespaces are used to separate words, but if a compiler knows that [
]
are separate symbols, whitespaces are just ignored. The following lines mean the same:
delete[]arr;
delete []arr;
delete [] arr;
delete[] arr;
delete [ ] arr ;
newlines or tabs are also ignored:
delete
[
]
arr
;
They mean the same thing and do the same thing.
what is the logic behind the various ways and which way should be preferred?
The logic is maintainability and readability. No one wants to read hundreds of newlines between symbols and scroll a file thousand columns to the right to find a ;
. The programmer is responsible for making it's code readable for others so that the code can be later understood, so that it's easy to find bugs, to patch it, to continue with the development.
PS. There is no such thing for C++, but because C and C++ share most of the grammar rules, I think I could mention The International Obfuscated C Code Contest, where the goal is to write obfuscate code in C. Contestants often use the rules that you can put whitespaces between gramatic tokens and for example create images or stars or different shapes from the source code of their programs.
Upvotes: 3
Reputation: 40882
That depends on the coding guidelines of the project you are working on. But you most commonly use delete[]
, as it makes it visually clear at the first look that you delete an array.
Why is allowed to have those different writings, is something you need to ask the one involved in defining the syntax, maybe they weren't sure what the best style is and therefore allowed both.
Upvotes: 1