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.

2 comments:

Anonymous said...

I think you've pretty much nailed the answer!

Balbir said...

cool! these things are very interesting though. I spent some time last week doing a crash course in ruby and python - they seem to be good languages, but I cannot think of a way of ever implementing an efficient compiler for them :-)

I need to update my blog, its been a long time now :-)

Ranking and Unranking permutations

I've been a big fan of Skiena's Algorithm Design Manual , I recently found my first edition of the book (although I own the third ed...