Issue
I came across this C code that I can't explain to myself:
check_eeprom_data();
{
unsigned char serial_num[5];
printStr("\nSerNUM:");
eeprom_read(confEE_SERIAL_NUM, serial_num, 5);
printBuffAsHex(serial_num, 5);
}
Why are these curly brackets needed to enclose this part of the code? What makes it different if there were no brackets?
Solution
The curly brackets are there to allow easy parallel code structure. That is, suppose you wanted to do the same operation again. Without the curly brackets, you would not be able to cut and paste that code block, perhaps with modifications. It is because you can only declare serial_num once at the top of any scope. So it would come out like this:
unsigned char serial_num[5];
printStr("\nSerNUM:");
eeprom_read(confEE_SERIAL_NUM, serial_num, 5);
printBuffAsHex(serial_num, 5);
printStr("\nSerNUM:");
eeprom_read(confEE_SERIAL_NUM, serial_num, 5);
printBuffAsHex(serial_num, 5);
Notice how I can't declare serial_num again? So I can't even keep the block the same I have to delete the line. If I want to introduce a similar block before I would need to move the declaration up. If I wanted to change the length of serial_num I would be stuck because you can only declare serial_num once in any scope.
With curly braces I have a parallel visual structure (ideal for cut and paste with or without modifications) and I also have the flexibility to declare serial_num with different length in each scope.
{
unsigned char serial_num[5];
printStr("\nSerNUM:");
eeprom_read(confEE_SERIAL_NUM, serial_num, 5);
printBuffAsHex(serial_num, 5);
}
{
unsigned char serial_num[8];
printStr("\nSerNUM:");
eeprom_read(confEE_SERIAL_NUM, serial_num, 8);
printBuffAsHex(serial_num, 8);
}
Notice how the separate scopes allow one to handle each block independently without interference between them? So I can reorder the blocks even though they use the same symbol name serial_num and not worry about changing the declaration of serial_num. Indeed I can declare serial_num locally as appropriate for each block regardless of if the symbol name matches other blocks or not.
This common pattern is used to increase isolation among distinct local blocks of code that should not be interfering with each other with declarations leaking through from one block to the next. It protects you from symbol name collision and prevents accidental reuse of symbols when you want each block to retain a local flavor despite being similar to other blocks around it.
Answered By - Rudi Cilibrasi Answer Checked By - Marie Seifert (PHPFixing Admin)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.