Brace notation

From Wikipedia, the free encyclopedia

In several Programming languages, such as Perl, Brace Notation is a faster way to extract bytes from a string variable.

[edit] Pseudocode Example

An example of brace notation using pseudocode which would extract the 82'nd character from the string would be

 a_byte=a_string{82} 

The equivalent of this using a hypothetical function 'MID' would be

 a_byte=MID(a_string,82,1) 

[edit] Brace Notation in C

In C, strings are normally represented as a character array rather than an actual string data type. The fact a string is really an array of characters means that referring to a string would mean referring to the first element in an array. Hence in C, the following is a legitimate example of brace notation:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main(int argc, char* argv[]) {
       char* a_string = "Test";
       printf("%c",a_string[0]); // Would print "T"
       printf("%c",a_string[1]); // Would print "e"
       printf("%c",a_string[2]); // Would print "s"
       printf("%c",a_string[3]); // Would print "t"
       printf("%c",a_string[4]); // Would print the 'null' character (ASCII 0) for end of string
       return(0);
}

Note that each of a_string[n] would have a 'char' data type while a_string itself would return a pointer to the first element in the a_string character array.

[edit] Drawbacks

While this notation is much faster, it is also more dangerous because it does not perform any checks on string length, and therefore its return cannot be accurately predicted.

In particular, using brace notation without making sure you are within the limits of your string could have really nasty consequences for your program since if you read a character that's past the string terminator, you would be reading memory that's not allocated to that string. This memory could be another string, a pointer, or something completely different such as unallocated space. Writing to this space in memory would cause unpredictable results, and will probably end in a SIGSEGV (segmentation fault).