- Brace notation
In several
Programming language s, such asPerl , Brace Notation is a faster way to extractbyte s from a string variable.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)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
#include
#includeint 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.
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).
Wikimedia Foundation. 2010.