Monday, July 03, 2006

Simple C tidbits (tasty morsels)

I cam across the term tasty morsels in the book Expert C Programming: Deep C Secrets by Peter Van Der Linden. I have been thinking of accumulating them myself, the challenge is to avoid duplicates and keep them interesting

My friend Phani Babu asked me a simple question

"Can we declare static variables in a struct, if no why; if yes where will it be stored?"

My answer was

"We cannot from what I know. struct is a data type declaration keyword, specifying storage might not be acceptable there. But the case for c++ is different where you can have static variables in the class and later on define them outside with the syntax [type]: [class]:[var] [= value]"

The requirements for both languages are clearly different. C being a structured language had no support for methods within a structure or a class. With the addition of classes came the concept of instances of a class. With instances came the need to share data across instances. This could be done using global variables, but it would be ugly. The solution was to allow shared per class data across instances.

Any add-ons will be credited and appreciated.
Post a Comment