Awanish Welcomes You

awanish tripathi

Inspirational & Genius One and the Same

personality shapes your behavior

Tuesday, May 29, 2012

PHP 1-http://php.net/quickref.php 2- 3-http://www.answerbag.com/q_view/1200435 JAVA SCRIPT 1-http://www.tutorialspoint.com/javascript/javascript_builtin_functions.htm 2-http://www.w3schools.com/js/tryit.asp?filename=tryjs_form_validation MYSQL 1- http://www.w3schools.com/php/php_mysql_select.asp 2- http://www.w3schools.com/php/php_mysql_insert.asp 3- http://www.w3schools.com/php/php_mysql_update.asp 4- http://www.w3schools.com/php/php_mysql_delete.asp 5- http://www.w3schools.com/php/php_mysql_create.asp

Sunday, April 1, 2012

new

http://www.wduffy.co.uk/jscroll/

Friday, September 2, 2011

HOW TO HIDE OR SHOW DRIVES IN WINDOWS



How to hide hard drives in Windows XP/Vista/7



If you have sensitive or important data stored on a particular disk drive that you don’t want anyone to see, a great way to hide it is to remove the drive letter assigned to a particular mounted volume. With Windows XP, you can achieve this easily using nothing more than the Command Prompt. Here's how:


- Click Start >> Run (This brings up the Run dialog box)
- Type cmd and press Enter (This brings up the Windows Command Prompt)
- Type diskpart in the command prompt and press Enter (This launches the Diskpart utility within the Command Prompt window)
- Now type list volume (This displays a list of all mounted volumes on your computer and their associated drive letters)



for example, you would like to hide drive E, type select volume 6

- Now type remove letter E (Note: This sometime requires a reboot)

Diskpart will now remove the drive letter. The drive will no longer be available via Windows Explorer or My Computer.

Don’t worry though, your data remains safe!

Now, should you want to unhide the drive and make it accessible again, just repeat the above process. But instead of typing remove letter E, type assign letter E


ref(cyberst0rm.blogspot.com)

Friday, February 18, 2011

What do you mean by shadowing in .NET?

What do you mean by shadowing in .NET?

Assume that you have a class that derives from the base class and redefines a method in the base class. Then what process is happening? You will generally assume it as overriding meaning that derived class method overrides base class method and redefines the method.






Even when it redefines, the derived class method should have the same signature as base class method and the derived class method should include the keyword override in its method signature.
What if you don’t explicitly specify the override keyword in your derived class method? Even then does it mean as overriding. No, if you don’t explicitly use override then the derived class method is shadowing base class method. This means that derived class is creating a new method that is no way related to the base class method. But the derived class method completely shadows/hides base class method. Unlike overriding, members sharing same name in derived class can have a totally different signature since it is a new member.

Shadowing happens by default when two members share the same name but override keyword is not mentioned. However you can explicitly perform shadowing using a keyword.

The keyword differs between languages:
• In C#, shadowing is done by using new modifier
• In VB.NET, shadowing is done using shadows keyword

Given below are examples to demonstrate shadowing in both the languages.

Shadowing in C#:
In the following example, method displayMsg of baseClass and data member called member are shadowed by the derived class members using the new modifier:
class baseClass {
public int member;
baseClass(int data) {
member = data;
}
public void displayMsg() {
Console.WriteLine(“In baseClass..”);
}
}
class derivedClass:baseClass {
new public string member;
public derivedClass(string data) {
member = data;
}
new public void displayMsg(string msg) {
Console.WriteLine(“In derivedClass with msg:”+msg);
}
}
class testClass {
baseClass bObj = new baseClass(100);
Console.WriteLine(“Member value of bObj is:” + bObj.member);
bObj.displayMsg();
derivedClass dObj = new derivedClass(“Hello”);
Console.WriteLine(“Member value of dObj is:” + dObj.member);
dObj.displayMsg(“Good Day!”);
}
Output of this code will be:
Member value of bObj is: 100
In baseClass..
Member value of dObj is: Hello
In derivedClass with msg: Good Day!

In this example, derived class has completely shadowed member and displayMsg of baseClass. Note that the signature of member and displayMsg is different in derivedClass when compared to baseClass. This is acceptable in case of shadowing. But in overriding, it will throw error.

Shadowing in VB.NET:
In VB.NET, shadowing is done with the help of shadows keyword as demonstrated in the example shown below:
Public Class baseClass
Public member As Integer = 100
End Class

Public Class derivedClass
Inherits baseClass
Public Shadows member As String = “Hello”
End Class

Module testModule
Sub Main()
Dim bObj as New baseClass
Dim dObj as New derivedClass
MessageBox.Show(bObj.member)
MessageBox.Show(dObj.member)
End Sub
End Module

The MessageBox will display 100 first and then Hello.

Invoking Base Class Member Using Derived Class Object:
So far in the discussion, it was told that the baseClass member is completely hidden in derivedClass. Does that mean you cannot access the baseClass member in derivedClass? No. You still have an option using references. Given below is the modified code of testClass containing code to access baseClass member using derivedClass object:
Module testModule
Sub Main()
Dim dObj As New derivedClass
Dim refBaseClass As baseClass = dObj
MessageBox.Show(&refBaseClass.member)
End Sub
End Module

Now to your surprise, you will get the output as 100. This is because you create a reference to baseClass which is assigned with derivedClass object. Whatever is the assigned object, the reference takes priority and the baseClass member gets displayed. In this case, shadowing is suppressed.
Reference-dotnet-guide.com

SOME INPORTANT DATABASE QUESTION

What are two methods of retrieving SQL?
What cursor type do you use to retrieve multiple recordsets?
What is the difference between a "where" clause and a "having" clause? - "Where" is a kind of restiriction statement. You use where clause to restrict all the data from DB.Where clause is using before result retrieving. But Having clause is using after retrieving the data.Having clause is a kind of filtering command.
What is the basic form of a SQL statement to read data out of a table? The basic form to read data out of table is ‘SELECT * FROM table_name; ‘ An answer: ‘SELECT * FROM table_name WHERE xyz= ‘whatever’;’ cannot be called basic form because of WHERE clause.
What structure can you implement for the database to speed up table reads? - Follow the rules of DB tuning we have to: 1] properly use indexes ( different types of indexes) 2] properly locate different DB objects across different tablespaces, files and so on.3] create a special space (tablespace) to locate some of the data with special datatype ( for example CLOB, LOB and …)
What are the tradeoffs with having indexes? - 1. Faster selects, slower updates. 2. Extra storage space to store indexes. Updates are slower because in addition to updating the table you have to update the index.
What is a "join"? - ‘join’ used to connect two or more tables logically with or without common field.
What is "normalization"? "Denormalization"? Why do you sometimes want to denormalize? - Normalizing data means eliminating redundant information from a table and organizing the data so that future changes to the table are easier. Denormalization means allowing redundancy in a table. The main benefit of denormalization is improved performance with simplified data retrieval and manipulation. This is done by reduction in the number of joins needed for data processing.
What is a "constraint"? - A constraint allows you to apply simple referential integrity checks to a table. There are four primary types of constraints that are currently supported by SQL Server: PRIMARY/UNIQUE - enforces uniqueness of a particular table column. DEFAULT - specifies a default value for a column in case an insert operation does not provide one. FOREIGN KEY - validates that every value in a column exists in a column of another table. CHECK - checks that every value stored in a column is in some specified list. Each type of constraint performs a specific type of action. Default is not a constraint. NOT NULL is one more constraint which does not allow values in the specific column to be null. And also it the only constraint which is not a table level constraint.
What types of index data structures can you have? - An index helps to faster search values in tables. The three most commonly used index-types are: - B-Tree: builds a tree of possible values with a list of row IDs that have the leaf value. Needs a lot of space and is the default index type for most databases. - Bitmap: string of bits for each possible value of the column. Each bit string has one bit for each row. Needs only few space and is very fast.(however, domain of value cannot be large, e.g. SEX(m,f); degree(BS,MS,PHD) - Hash: A hashing algorithm is used to assign a set of characters to represent a text string such as a composite of keys or partial keys, and compresses the underlying data. Takes longer to build and is supported by relatively few databases.
What is a "primary key"? - A PRIMARY INDEX or PRIMARY KEY is something which comes mainly from
database theory. From its behavior is almost the same as an UNIQUE INDEX, i.e. there may only be one of each value in this column. If you call such an INDEX PRIMARY instead of UNIQUE, you say something about
your table design, which I am not able to explain in few words. Primary Key is a type of a constraint enforcing uniqueness and data integrity for each row of a table. All columns participating in a primary key constraint must possess the NOT NULL property.
What is a "functional dependency"? How does it relate to database table design? - Functional dependency relates to how one object depends upon the other in the database. for example, procedure/function sp2 may be called by procedure sp1. Then we say that sp1 has functional dependency on sp2.
What is a "trigger"? - Triggers are stored procedures created in order to enforce integrity rules in a database. A trigger is executed every time a data-modification operation occurs (i.e., insert, update or delete). Triggers are executed automatically on occurance of one of the data-modification operations. A trigger is a database object directly associated with a particular table. It fires whenever a specific statement/type of statement is issued against that table. The types of statements are insert,update,delete and query statements. Basically, trigger is a set of SQL statements A trigger is a solution to the restrictions of a constraint. For instance: 1.A database column cannot carry PSEUDO columns as criteria where a trigger can. 2. A database constraint cannot refer old and new values for a row where a trigger can.
Why can a "group by" or "order by" clause be expensive to process? - Processing of "group by" or "order by" clause often requires creation of Temporary tables to process the results of the query. Which depending of the result set can be very expensive.
What is "index covering" of a query? - Index covering means that "Data can be found only using indexes, without touching the tables"
What types of join algorithms can you have?
What is a SQL view? - An output of a query can be stored as a view. View acts like small table which meets our criterion. View is a precomplied SQL query which is used to select data from one or more tables. A view is like a table but it doesn’t physically take any space. View is a good way to present data in a particular format if you use that query quite often. View can also be used to restrict users from accessing the tables directly.

Saturday, January 22, 2011

भारतीय गणन परंपरा : प्रामाणिक और चमत्कारी

ND
क्या यह संभव है कि जिस भारत ने हजारों साल पहले दुनिया को शून्य और दशमलव प्रणाली दी है, उसके पास अपना कोई अलग गणित-ज्ञान न रहा हो? जिन वेदों की गागर में अपने समय के समूचे ज्ञान-विज्ञान का महासागर भरा हो, उस में गणित-ज्ञान नाम की सरिता के लिए स्थान न बचा हो?

जर्मनी में सबसे कम समय का एक नियमित टेलीविजन कार्यक्रम है 'विसन फोर अख्त।' हिंदी में अर्थ हुआ 'आठ के पहले ज्ञान की बातें'। देश के सबसे बड़े रेडियो और टेलीविजन नेटवर्क एआरडी के इस कार्यक्रम में, हर शाम आठ बजे होने वाले मुख्य समाचारों से ठीक पहले, भारतीय मूल के विज्ञान पत्रकार रंगा योगेश्वर केवल दो मिनटों में ज्ञान-विज्ञान से संबंधित किसी दिलचस्प प्रश्न का सहज-सरल उत्तर देते हैं। ऐसे ही एक कार्यक्रम में रंगा योगेश्वर बता रहे थे कि भारत की क्या अपनी कोई अलग गणित है? वहाँ के लोग क्या किसी दूसरे ढंग से हिसाब लगाते हैं?

देखिए उदाहरण :
multiply 23 by 12:

2 3
| × |
1 2
2×1 2×2+3×1 3×2

2_____7_____6

So 23 × 12 = 276

भारत में कम ही लोग जानते हैं कि वैदिक गणित नाम का भी कोई गणित है। जो जानते भी हैं, वे इसे विवादास्पद मानते हैं कि वेदों में किसी अलग गणना प्रणाली का उल्लेख है। पर विदेशों में बहुत-से लोग मानने लगे हैं कि भारत की प्राचीन वैदिक विधि से गणित के हिसाब लगाने में न केवल मजा आता है, उससे आत्मविश्वास मिलता है और स्मरणशक्ति भी बढ़ती है। मन ही मन हिसाब लगाने की यह विधि भारत के स्कूलों में शायद ही पढ़ाई जाती है। भारत के शिक्षाशास्त्रियों का अब भी यही विश्वास है कि असली ज्ञान-विज्ञान वही है, जो इंग्लैंड-अमेरिका से आता है।


ND
घर का जोगी जोगड़ा
घर का जोगी जोगड़ा, आन गाँव का सिद्ध। जबकि सच्चाई यह है कि इंग्लैंड-अमेरिका जैसे आन गाँव वाले भी योगविद्या की तरह ही आज भारतीय वैदिक गणित पर चकित हो रहे हैं और उसे सीख रहे हैं। उसे सिखाने वाली पुस्तकों और स्कूलों की भरमार हो गई है। बिना कागज-पेंसिल या कैल्क्युलेटर के मन ही मन हिसाब लगाने का उससे सरल और तेज तरीका शायद ही कोई है। रंगा योगेश्वर ने जर्मन टेलीविजन दर्शकों को एक उदाहरण से इसे समझायाः

'मान लें कि हमें 889 में 998 का गुणा करना है। प्रचलित तरीके से यह इतना आसान नहीं है। भारतीय वैदिक तरीके से उसे ऐसे करेंगेः दोनों का सब से नजदीकी पूर्णांक एक हजार है। उन्हें एक हजार में से घटाने पर मिले 2 और 111 । इन दोनों का गुणा करने पर मिलेगा 222 । अपने मन में इसे दाहिनी ओर लिखें। अब 889 में से उस दो को घटाएँ, जो 998 को एक हजार बनाने के लिए जोड़ना पड़ा। मिला 887। इसे मन में 222 के पहले बाईं ओर लिखें। यही, यानी 887 222, सही गुणनफल है।'

यूनान और मिस्र से भी पुराना
भारत का गणित-ज्ञान यूनान और मिस्र से भी पुराना बताया जाता है। शून्य और दशमलव तो भारत की देन हैं ही, कहते हैं कि यूनानी गणितज्ञ पाइथागोरस का प्रमेय भी भारत में पहले से ज्ञात था। लेकिन, यह ज्ञान समय की धूल के नीचे दबता गया। उसे झाड़-पोंछ कर फिर से निकाला पुरी के शंकराचार्य रहे स्वामी भारती कृष्णतीर्थजी महाराज ने 1911 से 1918 के बीच। वे एक विद्वान पुरुष थे। संस्कृत और दर्शनशास्त्र के अलावा गणित और इतिहास के भी ज्ञाता थे। सात विषयों में मास्टर्स (MA) की डिग्री से विभूषित थे। उन्होंने पुराने ग्रंथों और पांडुलिपियों का मंथन किया और निकाले वे सूत्र, जिन के आधार पर वैदिक विधि से मन ही मन हिसाब लगाये जा सकते हैं।

16 Sutras + 14 subsutras = 1 Amazingly Fast Calculating System! (एक विज्ञापन)

विधि के विरोध के आगे विवश
लगता है कि विधि के विधान को भी गणित की वैदिक विधि के विस्तार से कुछ विरोध था। कहा जाता है कि भारती कृष्णतीर्थजी ने वैदिक गणित के 16 मूल सूत्रों की व्याख्या करने वाली 16 पुस्तकों की पांडुलिपियाँ लिखीं थीं, पर वे कहीं गुम हो गईं या नष्ट हो गईं। उन्होंने ये पांडुलिपियाँ अपने एक शिष्य को संभाल कर रखने के लिए दी थीं। उन के खोजे सूत्र अंकगणित ही नहीं, बीजगणित और भूमिति सहित गणित की हर शाखा से संबंधित थे।

अपने अंतिम दिनों में उन्होंने एक बार फिर यह भगीरथ प्रयास करना चाहा, लेकिन विधि के विधान ने एक बार फिर टाँग अड़ा दी। वे केवल एक ही सूत्र पर दुबारा लिख पाए। उन्होंने जो कुछ लिखा था और उनके शिष्यों ने उनसे जो सीखा- सुना था, उसी के संकलन के आधार पर 1965 में वैदिक गणित नाम से एक पुस्तक प्रकाशित होने वाली थी। प्रकाशन से पहले ही बीमारी के कारण उनका जीवनकाल (1884 से 1960) पूरा हो चुका था।


ND
पश्चिम की बढ़ती दिलचस्पी
1960 वाले दशक के अंतिम दिनों में वैदिक गणित की एक प्रति जब लंदन पहुँची, तो इंग्लैंड के जाने-माने गणितज्ञ भी चकित रह गये। उन्होंने उस पर टिप्पणियाँ लिखीं और व्याख्यान दिए। जिन्हें 1981 में पुस्तकाकार प्रकाशित किया गया। यहीं से शुरू होता है पश्चिमी देशों में वैदिक गणित का मान-सम्मान और प्रचार-प्रसार।

कुछ साल पहले लंदन के सेंट जेम्स स्कूल ने अपने यहाँ वैदिक गणित की पढ़ाई शुरू की। आज उसे भारत से अधिक इंग्लैंड, अमेरिका, कनाडा और ऑस्ट्रेलिया जैसे देशों के सरकारी और निजी स्कूलों में पढ़ाया जाता है। शिक्षक गणित को रोचक और सरल बनाने के लिए उसका सहारा लेते हैं। वैदिक विधि से बड़ी संख्याओं का जोड़-घटाना और गुणा-भाग ही नहीं, वर्ग और वर्गमूल, घन और घनमूल निकालना भी संभव है।

नासा की जिज्ञासा
ऑस्ट्रेलिया के कॉलिन निकोलस साद वैदिक गणित के भक्त हैं। उन्होंने अपना उपनाम 'जैन' रख लिया है और ऑस्ट्रेलिया के न्यू साउथ वेल्स प्रांत में बच्चों को वैदिक गणित सिखाते हैं। उनका दावा हैः 'अमेरिकी अंतरिक्ष अधिकरण नासा गोपनीय तरीके से वैदिक गणित का कृत्रिम बुद्धिमत्ता वाले रोबोट बनाने में उपयोग कर रहा है। नासा वाले समझना चाहते हैं कि रोबोट में आदमी के दिमाग की नकल कैसे की जा सकती है ताकि रोबोट ही दिमाग की तरह हिसाब भी लगा सके-- उदाहरण के लिए कि 96 गुणा 95 कितना हुआ....9120।'

कॉलिन निकोलस साद ने वैदिक गणित पर किताबें भी लिखी हैं। बताते हैं कि वैदिक गणित कम से कम ढाई से तीन हजार साल पुराना विज्ञान है। उस में मन ही मन हिसाब लगाने के जो16 सूत्र बताए गए हैं, वे इस विधि का उपयोग करने वाले की स्मरणशक्ति भी बढ़ाते हैं।

चमकदार प्राचीन विद्या
साद अपने बारे में कहते हैं, 'मेरा काम अंकों की इस चमकदार प्राचीन विद्या के प्रति बच्चों में प्रेम जगाना है। मेरा मानना है कि बच्चों को सचमुच वैदिक गणित सीखना चाहिए। भारतीय योगियों ने उसे हजारों साल पहले विकसित किया था। आप उनसे गणित का कोई भी प्रश्न पूछ सकते थे और वे मन की कल्पनाशक्ति से देख कर फट से जवाब दे सकते थे। उन्होंने तीन हजार साल पहले शून्य की अवधारणा प्रस्तुत की और दशमलव वाला बिंदु सुझाया। उनके बिना आज हमारे पास कंप्यूटर नहीं होता।'

साद उर्फ जैन ने मानो वैदिक गणित के प्रचार-प्रसार का व्रत ले रखा है,' मैं पिछले 25 सालों से लोगों को बता रहा हूँ कि आप अपने बच्चों के लिए सबसे अच्छा काम यही कर सकते हैं कि उन्हें वैदिक गणित सिखाएँ। इससे आत्मविश्वास, स्मरणशक्ति और कल्पनाशक्ति बढ़ती है। इस गणित के 16 मूल सूत्र जानने के बाद

Thursday, January 20, 2011

C Vs C++



Incompatibilities Between

C and C++



Contents

Introduction
C++ versus C
Changes to C99 versus C++98
Aggregate Initializers
Comments
Conditional expression declarations
Digraph punctuation tokens
Implicit function declarations
Implicit variable declarations
Intermixed declarations and statements
C99 versus C++98
Alternate punctuation token spellings
Array parameter qualifiers
Boolean type
Character literals
clog identifier
Comma operator results
Complex floating-point type
Compound literals
const linkage
Designated initializers
Duplicate typedefs
Dynamic sizeof evaluation
Empty parameter lists
Empty preprocessor function macro arguments
Enumeration constants
Enumeration declarations with trailing comma
Enumeration types
Flexible array members
Function name mangling
Function pointers
Hexadecimal floating-point literals
IEC 60559 arithmetic support
Inline functions
Integer types headers
Library function prototypes
Library header files
long long integer type
Nested structure tags
Non-prototype function declarations
Old-style casts
One definition rule
_Pragma keyword
Predefined identifiers
Reserved keywords in C99
Reserved keywords in C++
restrict keyword
Returning void
static linkage
String initializers
String literals are const
Structures declared in function prototypes
Type-generic math functions
Typedefs versus type tags
Variable-argument function declarators
Variable-argument preprocessor function macros
Variable-length arrays
Void pointer assignments
Wide character type
References
Acknowledgments
Revision History
Bottom

Introduction

The C programming language began to be standardized some time around 1985 by the ANSI X3J9 committee. Several years of effort went by, and in 1989 ANSI approved the new standard. An ISO committee ratified it a year later in 1990 after adding an amendment dealing with internationalization issues. The 1989 C standard is known officially as ANSI/ISO 9899-1989, Programming Languages - C, and this document refers to the 1989 C standard as C89. The 1990 ISO revision of the standard is known officially as ISO/IEC 9899-1990, Programming Languages - C, which is referred to in this document as "C90".

The next version of the C standard was ratified by ISO in 1999. Officially know as ISO/IEC 9899-1999, Programming Languages - C, it is referred to in this document as "C99".

The C++ programming language was based on the C programming language as it existed shortly after the ANSI C standardization effort had begun. Around 1995 an ISO committee was formed to standardize C++, and the new standard was ratified in 1998, which is officially known as ISO/IEC 14882-1998, Programming Languages - C++. It is referred to in this document as "C++98" or simply as "C++".

Though the two languages share a common heritage, and though the designers involved in the standardization processes for each language tried to keep them as compatible as possible, some incompatibilities unavoidably arose. Once the programmer is aware of these potential problem spots, they are easy, for the most part, to avoid when writing C code.

When we say that C is incompatible with C++ with respect to a specific language feature, we mean that a C program that employs that feature either is not valid C++ code and thus will not compile as a C++ program, or that it will compile as a C++ program but will exhibit different behavior than the same program compiled as a C program. In other words, an incompatible C feature is valid as C code but not as C++ code. All incompatibilities of this kind are addressed in this document. Avoiding these kinds of incompatibilities allows the programmer to write correct C code that is intended to interact with, or be compiled as, C++ code.

Another form of incompatible feature is one that is valid when used in a C++ program but is invalid in a C program. We call this an incompatible C++ feature. Huge portions of the C++ language fall into this category (e.g., classes, templates, exceptions, references, member functions, anonymous unions, etc.), so very few of these kinds of incompatibilities are addressed in this document.

Yet another form of incompatible feature occurs when a C++ program uses a feature that has the same name as a C90 feature but which has a different usage or meaning in C. This document covers these kinds of incompatibilities.

This document lists only the incompatibilities between C99 and C++98. (Incompatibilities between C90 and C++ have been documented elsewhere; see Appendix B of Stroustrup [STR], for example.)

New additions to the C99 standard library are also not addressed in this document unless they specifically introduce C++ incompatibilities.
C++ versus C

As discussed in the Introduction, no attempt is made in this document to cover incompatible C++ features, i.e., features of the C++ language or library that are not supported in C. Huge portions of C++ and its library fall into this category. A partial list of these features includes:

anonymous unions
classes
constructors and destructors
exceptions and try/catch blocks
external function linkages (e.g., extern "C")
function overloading
member functions
namespaces
new and delete operators and functions
operator overloading
reference types
standard template library (STL)
template classes
template functions

Changes to C99 versus C++98

The following items are incompatibilities between C90 and C++98, but have since been changed in C99 so that they no longer cause problems between the two languages.

Aggregate Initializers
C90 requires automatic and register variables of aggregate type (struct, array, or union) to have initializers containing only constant expressions. (Many compilers do not adhere to this restriction, however.)

C99 removes that restriction, allowing non-constant expressions to be used in such initializers.

C++ allows non-constant expressions to be used in initializers for automatic and register variables. (It also allows arbitrary non-constant expressions to be used to initialize static and external variables.)

For example:

// C and C++ code
void foo(int i)
{
float x = (float)i; // Valid C90, C99, and C++
int m[3] = { 1, 2, 3 }; // Valid C90, C99, and C++
int g[2] = { 0, i }; // Invalid C90
}
[C99: §6.7.8]
[C++98: §3.7.2, 8.5, 8.5.1]

Comments
C++ recognizes //... comments as well as /*...*/ comments.

C90 only recognizes the /*...*/ form of comments. The //... form usually produces a syntax error in C90, but there are rare cases that may compile erroneously without warning:

i = (x//*y*/z++
, w);
C99 recognizes both forms of comments.

[C99: §5.1.1.2, 6.4.9]
[C++98: §2.1, 2.7]

Conditional expression declarations
C++ allows local variable declarations within conditional expressions (which appear within for, if, while, and switch statements). The scope of the variables declared in this context extends to the end of the statement containing the conditional expression. For example:

for (int i = 0; i < SIZE; i++)
a[i] = i + 1;
C90 does not allow this feature.

C99 allows this feature, but only within for statements.

[C99: §6.8.5]
[C++98: §3.3.2, 6.4, 6.5]

Digraph punctuation tokens
C++ recognizes two-character punctuation tokens, called digraphs, which are not recognized by C90. The digraphs and their equivalent tokens are:

<: [
:> ]
<% {
%> }
%: #
%:%: ##
C99 recognizes the same set of digraphs.

The following program is valid in both C99 and C++:

%:include

%:ifndef BUFSIZE
%:define BUFSIZE 512
%:endif

void copy(char d<::>, const char s<::>, int len)
<%
while (len-- >= 0)
<%
d<:len:> = s<:len:>;
%>
%>
[C99: §6.4.6]
[C++98: §2.5, 2.12]

Implicit function declarations
C90 allows a function to be implicitly declared at the point of its first use (call), assigning it a return type of int by default. For example:

/* No previous declaration of bar() is in scope */

void foo(void)
{
bar(); /* Implicit declaration: extern int bar() */
}
C++ does not allow implicit function declarations. It is invalid to call a function that does not have a previous declaration in scope.

C99 no longer allows functions to be implicitly declared. The code above is invalid in both C99 and C++.

[C99: §6.5.2.2]
[C++98: §5.2.2]

Implicit variable declarations
C90 allows the declaration of a variable, function argument, or structure member to omit the type specifier, implicitly defaulting its type to int.

C99 does not allow this omission, and neither does C++.

The following code is valid in C90, but invalid in C99 and C++:

static sizes = 0; /* Implicit int, error */

struct info
{
const char * name;
const sz; /* Implicit int, error */
};

static foo(register i) /* Implicit ints, error */
{
auto j = 3; /* Implicit int, error */

return (i + j);
}
[C99: §6.7, 6.7.2]
[C++98: §7, 7.1.5]

Intermixed declarations and statements
C90 syntax specifies that all the declarations within a block must appear before the first statement in the block.

C++ does not have this restriction, allowing statements and declarations to appear in any order within a block.

C99 also removes this restriction, allowing intermixed statements and declarations.

void prefind(void)
{
int i;

for (i = 0; i < SZ; i++)
if (find(arr[i]))
break;

const char * s; /* Invalid C90, valid C99 and C++ */

s = arr[i];
prepend(s);
}
[C99: §6.8.2]
[C++98: §6, 6.3, 6.7]


C99 versus C++98

The following items comprise the differences between C99 and C++98. Some of these incompatibilities existed between C89 and C++98 and remain unchanged between C99 and C++98, while others are new features that were introduced into C99 that are incompatible with C++98.

Note that features that are specific to C++ and which are not legal C (e.g., class member function declarations) are not included in this section; only language features that are common to both C and C++ are discussed. Most of the features are valid as C but invalid as C++.

Some of these features are likely to be implemented as extensions by many C++ compilers in order to be more compatible with C compilers.

Alternate punctuation token spellings
C++ provides the following keywords as synonyms for punctuation tokens:

and &&
and_eq &=
bitand &
bitor |
compl ~
not !
not_eq !=
or ||
or_eq |=
xor ^
xor_eq ^=
These keywords are also recognized by the C++ preprocessor.

C90 does not have these built-in keywords, but it does provide a standard header file that contains definitions for the same words as macros, behaving almost like built-in keywords.

C++ requires implementations to provide an empty header. Including it in a C++ program has no effect on the program. However, C code that does not include the header is free to use these words as identifiers and macro names, which may cause incompatibilities when such code is compiled as C++.

enum oper { nop, and, or, eq, ne };

extern int instr(enum oper op, struct compl *c);
The recommended practice for code intended to be compiled as both C and C++ is to use these identifiers only for these special meanings, and only after including .

// Proper header inclusion allows for the use of 'and' et al

#ifndef __cplusplus
#include
#endif

int foo(float a, float b, float c)
{
return (a > b and b <= c);
}
[C99: §7.9]
[C++98: §2.5, 2.11]

Array parameter qualifiers
C99 provides new declaration syntax for function parameters of array types, allowing type qualifiers (the cv-qualifiers const and volatile, and restrict) to be included within the first set of brackets of an array declarator. The qualifier modifies the type of the array parameter itself. For example, the following declarations are semantically identical:

extern void foo(int str[const]);
extern void foo(int *const str);
In both declarations, parameter str is a const pointer to an int object.

C99 also allows the static specifier to be placed within the brackets of an array declaration immediately preceding the expression specifying the size of the array. The presence of such a specifer indicates that the array is composed of at least the number of contiguous elements indicated by the size expression. (Presumably this is a hint to the compiler for optimizing access to elements of the array.) For example:

void baz(char s[static 10])
{
// s[0] thru s[9] exist and are contiguous
...
}
None of these new syntactic features are recognized by C++.

(These features might be provided as an extension by some C++ compilers.)

[C99: §6.7.5, 6.7.5.2, 6.7.5.3]
[C++98: §7.1.1, 7.1.5.1, 8.3.4, 8.3.5, 8.4]

Boolean type
C99 supports the _Bool keyword, which declares a two-valued integer type (capable of representing the values true and false). It also provides a standard header that contains definitions for the following macros:

bool Same as _Bool
false Equal to (_Bool)0
true Equal to (_Bool)1
C++ provides bool, false, and true as reserved keywords and implements bool as a true built-in boolean type.

C programs that do not include the header are free to use these keywords as identifiers and macro names, which may cause compatibility problems when such code is compiled as C++. For example:

typedef short bool; // Different

#define false ('\0') // Different
#define true (!false) // Different

bool flag = false;
The recommended practice is therefore to use these identifiers in C only for these special meanings, and only after including .

(It is likely that an empty header will be provided by most C++ implementations as an extension.)

[C99: §6.2.5, 6.3.1.1, 6.3.1.2, 7.16, 7.26.7]
[C++98: §2.11, 2.13.5, 3.9.1]

Character literals
In C, character literals such as 'a' have type int, and thus sizeof('a') is equal to sizeof(int).

In C++, character literals have type char, and thus sizeof('a') is equal to sizeof(char).

This difference can lead to inconsistent behavior in some code that is compiled as both C and C++.

memset(&i, 'a', sizeof('a')); // Questionable code
In practice, this is probably not much of a problem, since character constants are implicitly converted to type int when they appear within expressions in both C and C++.

[C99: §6.4.4.4]
[C++98: §2.13.2]

clog identifier
C99 declares clog() in as the complex natural logarithm function.

C++ declares std::clog in as the name of the standard error logging output stream (analogous to the stderr stream). This name is placed into the global namespace if the header is included, and refers to the logarithm function. If defines clog as a preprocessor macro name, it can cause problems with other C++ code.

// C++ code

#include
using std::clog;

#include // Possible conflict

void foo(void)
{
clog << clog(2.718281828) << endl;
// Possible conflict
}
Including both the and the headers in C++ code places both clog names into the std:: namespace, one being a variable and the other being a function, which should not cause any conflicts.

// C++ code

#include
#include

void foo(void)
{
std::clog << std::clog(2.718281828) << endl;
// No conflict; different types
}

void bar(void)
{
complex double (* fp)(complex double);

fp = &std::clog; // Unambiguous
}
It would appear that the safest approach to this potential conflict would be to avoid using both forms of clog within the same source file.

[C99: §7.3.7.2]
[C++98: §27.3.1]

Comma operator results
The comma operator in C always results in an r-value even if its right operand is an l-value, while in C++ the comma operator will result in an l-value if its right operand is an l-value. This means that certain expressions are valid in C++ but not in C:

int i;
int j;

(i, j) = 1; // Valid C++, invalid C
[C99: §6.5.3.4, 6.5.17]
[C++98: §5.3.3, 5.18]

Complex floating-point type
C99 provides built-in complex and imaginary floating point types, which are declared using the _Complex and _Imaginary keywords.

There are exactly three complex types and three imaginary types in C99:

_Complex float
_Complex double
_Complex long double

_Imaginary long double
_Imaginary double
_Imaginary long double
C99 also provides a standard header that contains definitions of complex floating point types, macros, and constants. In particular, this header defines the following macros:

complex Same as _Complex
imaginary Same as _Imaginary
I i (the complex identity)
C code that does not include this header is free to use these words as identifiers and macro names. This was an intentional part of the design of the _Complex and _Imaginary keywords, since this allows existing code that employs the new words to continue working as it did before under C89.

Implicit widening conversions between the complex and imaginary types are provided, which parallel the implicit widening conversions between the non-complex floating point types.

// C99 code

#include

complex double square_d(complex double a)
{
return (a * a);
}

complex float square_f(complex float a)
{
complex double d = a; // Implicit conversion

return square_d(a); // Implicit conversion
}
C++ provides a template class named complex, declared in the standard header file. This type is incompatible with the C99 complex types.

C++ supports more complex types than C99, in theory, since complex is a template class.

// C++ code

#include

complex square(complex a)
{
return (a * a);
}

complex square(complex a)
{
return (a * a);
}
It is possible to define typedefs that will work in both C99 and C++, albeit with some limitations:

#ifdef __cplusplus

#include

typedef complex complex_float;
typedef complex complex_double;
typedef complex complex_long_double;

#else

#include

typedef complex float complex_float;
typedef complex double complex_double;
typedef complex long double complex_long_double;

typedef imaginary float imaginary_float;
typedef imaginary double imaginary_double;
typedef imaginary long double imaginary_long_double;

#endif
Including these definitions allows for portable code that will compile as both C and C++ code, such as:

complex_double square_cd(complex_double a)
{
return (a * a);
}
[C99: §6.2.5, 6.3.1.6, 6.3.1.7, 6.3.1.8]
[C++98: §26.2]

Compound literals
C99 allows literals having types other than primitive types (e.g., user-defined structure or array types) to be specified in constant expressions; these are called compound literals. For example:

struct info
{
char name[8+1];
int type;
};

extern void add(struct info s);
extern void move(float coord[2]);

void predef(void)
{
add((struct info){ "e", 0 }); // A struct literal
move((float[2]){ +0.5, -2.7 }); // An array literal
}
C++ does not support this feature.

C++ does provides a similar capability through the use of non-default class constructors, but which is not quite as flexible as the C feature:

void predef2()
{
add(info("e", 0)); // Call constructor info::info()
}
(This C feature might be provided as an extension by some C++ compilers, but would probably be valid only for POD structure types and arrays of POD types.)

[C99: §6.5.2, 6.5.2.5]
[C++98: §5.2.3, 8.5, 12.1, 12.2]

const linkage
C specifies that a variable declared with a const qualifier is not a modifiable object. In all other regards, though, it is treated the same as any other variable. Specifically, if a const object with file scope is not explicitly declared static, its name has external linkage and is visible to other source modules.

const int i = 1; // External linkage

extern const int j = 2; // 'extern' optional
static const int k = 3; // 'static' required
C++ specifies that a const object with file scope has internal linkage by default, meaning that the object's name is not visible outside the source file in which it is declared. A const object must be declared with an explicit extern specifier in order to be visible to other source modules.

const int i = 1; // Internal linkage

extern const int j = 2; // 'extern' required
static const int k = 3; // 'static' optional
The recommended practice is therefore to define constants with an explicit static or extern specifier.

[C99: §6.2.2, 6.7.3]
[C++98: §7.1.5.1]

Designated initializers
C99 introduces the feature of designated initializers, which allows specific members of structures, unions, or arrays to be initialized explicitly by name or subscript. For example:

struct info
{
char name[8+1];
int sz;
int typ;
};

struct info arr[] =
{
[0] = { .sz = 20, .name = "abc" },
[9] = { .sz = -1, .name = "" }
};
Unspecified members are default-initialized.
C++ does not support this feature.

(This feature might be provided as an extension by some C++ compilers, but would probably be valid only for POD structure types and arrays of POD types. However, C++ already provides a similar capability through the use of non-default class constructors.)

[C99: §6.7.8]
[C++98: §8.5.1, 12.1]

Duplicate typedefs
C does not allow a given typedef to appear more than once in the same scope.

C++ handles typedefs and type names differently than C, and allows redundant occurrences of a given typedef within the same scope.

Thus the following code is valid in C++ but invalid in C:

typedef int MyInt;
typedef int MyInt; // Valid C++, invalid C
This means that typedefs that might be included more than once in a program (e.g., common typedefs that occur in multiple header files) should be guarded by preprocessing directives if such source code is meant to be compiled as both C and C++. For example:

//========================================
// one.h

#ifndef MYINT_T
#define MYINT_T
typedef int MyInt;
#endif
...

//========================================
// two.h

#ifndef MYINT_T
#define MYINT_T
typedef int MyInt;
#endif
...
Thus code can include multiple header files without causing an error in C:

// Include multiple headers that define typedef MyInt
#include "one.h"
#include "two.h"

MyInt my_counter = 0;
[C99: §6.7, 6.7.7]
[C++98: §7.1.3]

Dynamic sizeof evaluation
Because C99 supports variable-length arrays (VLAs), the sizeof operator does not necessarily evaluate to a constant (compile-time) value. Any expression that involves applying the sizeof operator to a VLA operand must be evaluated at runtime (any other use of sizeof can be evaluated at compile time). For example:

size_t dsize(int sz)
{
float arr[sz]; // VLA, dynamically allocated

if (sz <= 0)
return sizeof(sz); // Evaluated at compile time
else
return sizeof(arr); // Evaluated at runtime
}
C++ does not support VLAs, so C code that applies the sizeof operator to VLA operands will cause problems when compiled as C++.

[C99: §6.5.3.4, 6.7.5, 6.7.5.2]
[C++98: §5.3, 5.3.3]

Empty parameter lists
C distinguishes between a function declared with an empty parameter list and a function declared with a parameter list consisting of only void. The former is an unprototyped function taking an unspecified number of arguments, while the latter is a prototyped function taking no arguments.

// C code

extern int foo(); // Unspecified parameters
extern int bar(void); // No parameters

void baz()
{
foo(0); // Valid C, invalid C++
foo(1, 2); // Valid C, invalid C++

bar(); // Okay in both C and C++
bar(1); // Error in both C and C++
}
C++, on the other hand, makes no distinction between the two declarations and considers them both to mean a function taking no arguments.

// C++ code

extern int xyz();

extern int xyz(void); // Same as 'xyz()' in C++,
// Different and invalid in C
For code that is intended to be compiled as either C or C++, the best solution to this problem is to always declare functions taking no parameters with an explicit void prototype. For example:

// Compiles as both C and C++
int bosho(void)
{
...
}
Empty function prototypes are a deprecated feature in C99 (as they were in C89).

[C99: §6.7.5.3]
[C++98: §8.3.5, C.1.6.8.3.5]

Empty preprocessor function macro arguments
C99 allows preprocessor function macros to be specified with empty (missing) arguments.

#define ADD3(a,b,c) (+ a + b + c + 0)

ADD3(1, 2, 3) => (+ 1 + 2 + 3 + 0)
ADD3(1, 2, ) => (+ 1 + 2 + + 0)
ADD3(1, , 3) => (+ 1 + + 3 + 0)
ADD3(1,,) => (+ 1 + + + 0)
ADD3(,,) => (+ + + + 0)
C++ does not support empty preprocessor function macros arguments.

(This feature is likely to be provided as an extension by many C++ compilers.)

[C99: §6.10.3, 6.10.3.1]
[C++98: §16.3., 16.3.1]

Enumeration constants
Enumeration constants in C are essentially just named constants of type signed int. As such, they are constrained to having an initialization value that falls within the range [INT_MIN,INT_MAX]. This also means that for any given enumeration constant RED, the values of sizeof(RED) and sizeof(int) are always the same.

C++ enumeration constants have the same type as their enumeration type, which means that they have the same size and alignment as their underlying integer type. This means that the values of sizeof(RED) and sizeof(int) are not necessarily the same for any given enumeration constant RED. Enumeration constants also have a wider range of possible underlying types in C++ than in C: signed int, unsigned int, signed long, and unsigned long. As such, they also have a wider range of valid initialization values.

This may cause incompatibilities for C code compiled as C++, if the C++ compiler chooses to implement an enumeration type as a different size than it would be in C, or if the program relies on the results of expressions such as sizeof(RED).

enum ControlBits
{
CB_LOAD = 0x0001,
CB_STORE = 0x0002,
...
CB_TRACE = LONG_MAX+1, // (Undefined behavior)
CB_ALL = ULONG_MAX
};
[C99: §6.4.4.3, 6.7.2.2]
[C++98: §4.5, 7.2]

Enumeration declarations with trailing comma
C99 allows a trailing comma to follow the last enumeration constant initializer within an enumeration type declaration, similar to structure member initialization lists. For example:

enum Color { RED = 0, GREEN, BLUE, };
C++ does not allow this.

(This feature is likely to be provided as an extension by many C++ compilers.)

[C99: §6.7.2.2]
[C++98: §7.2]

Enumeration types
C specifies that each enumerated type is a unique type, distinct from all other enumerated types within the same program. The implementation is free to use a different underlying primitive integer type for each enumerated type. This means that sizeof(enum A) and sizeof(enum B) are not necessarily the same. This also means, given that RED is an enumeration constant of type enum Color, that sizeof(RED) and sizeof(enum Color) are not necessarily the same (since all enumeration constants are of type signed int).

All enumeration constants, though, convert to values of type signed int when they appear in expressions. Since enumeration constants cannot portably be wider than int, it might appear that int is the widest enumeration type; however, implementations are free to support wider enumeration integer types. Such extended types may be different than the types used by a C++ compiler, however.

In C, objects of enumeration types may be assigned integer values without the need for a explicit cast. For example:

// C code

enum Color { RED, BLUE, GREEN };

int c = RED; // Cast not needed
enum Color col = 1; // Cast not needed
C++ also specifies that all enumerated types are unique and distinct types, but it goes further than C to enforce this. In particular, a function name can be overloaded to take an argument of different enumerated types. While objects of enumerated types implicitly convert to integer values, integer values require an explicit cast to be converted into enumerated types. Implicitly converted enumeration values are converted to their underlying integer type, which is not necessarily signed int. For example:

// C++ code

enum Color { ... };

enum Color setColor(int h)
{
enum Color c;

c = h; // Error, no implicit conversion
return c;
}

int hue(enum Color c)
{
return (c + 128); // Implicit conversion,
// but might not be signed int
}
Since a C++ enumeration constant has the same type and size as its enumeration type, this means, given that RED is an enumeration constant of type enum Color, that the values of sizeof(RED) and sizeof(enum Color) are exactly the same, which differs from the rules in C.

There is no guarantee that a given enumeration type is implemented as the same underlying type in both C and C++, or even in different C implementations. This affects the calling interface between C and C++ functions. This may also cause incompatibilities for C code compiled as C++, if the C++ compiler chooses to implement an enumeration type as a different size that it would be in C, or if the program relies on the results of expressions such as sizeof(RED).

// C++ code

enum Color { ... };

extern "C" void foo(Color c);
// Parameter types might not match

void bar(Color c)
{
foo(c); // Enum types might be different sizes
}
[C99: §6.4.4.3, 6.7.2.2]
[C++98: §4.5, 7.2]

Flexible array members (FAMs)
This is also known as the struct hack. This specifies a conforming way to declare a structure containing a set of fixed-sized members followed by a flexible array member that can hold an unspecified number of elements. Such a structure is typically allocated by calling malloc(), passing it the number of bytes beyond the fixed portion of the structure to add to the allocation size. For example:

struct Hack
{
int count; // Fixed member(s)
int fam[]; // Flexible array member
};

struct Hack * vmake(int sz)
{
struct Hack * p;

p = malloc(sizeof(struct Hack) + sz*sizeof(int));
// Allocate a variable-sized structure

p->count = sz;
for (int i = 0; i < sz; i++)
p->fam[i] = i;

return p;
}
C++ does not support flexible array members.

(This feature might be provided as an extension by some C++ compilers, but would probably be valid only for POD structure types.)

[C99: §6.7.2.1]
[C++98: §8.3.4]

Function name mangling
In order to implement overloaded functions and member functions, C++ compilers must have a means of mapping the source names of functions into unique symbols in the object code resulting from the compile. For example, the functions ::foo(int), ::foo(float), and Mine::foo() all have identical names (foo) but different calling signatures. In order for the linker to distinguish between the functions during program link time, they must be mangled into different symbolic names.

This differs from the way functions names are mapped into symbolic object names in C, which allows for certain cases of type punning (between signed and unsigned integer types) and non-prototyped extern functions. Therefore C programs compiled as C++ will produce different symbolic names, unless the functions are explicitly declared as having extern "C" linkage. For example:

int foo(int i); // Different symbolic names in C and C++

#ifdef __cplusplus
extern "C"
#endif
int bar(int i); // Same symbolic name in both C and C++
C++ functions are implicitly declared with extern "C++" linkage.

Another consequence of C++ function name mangling is that identifiers in C++ are not allowed to contain two or more consecutive underscores (e.g., the name foo__bar is invalid). Such names are reserved for the implementation, ostensibly so that it may have a guaranteed means of mangling source function names into unique object symbolic names. (For example, an implementation might choose to mangle the member function Mine::foo(int) into something like foo__4Mine_Fi, which is a symbolic name containing consecutive underscores.)

C does not reserve such names, so a C program is free to use such names in any manner. For example:

void foo__bar(int i) // Improper C++ name
{ ... }
[C99: §5.2.4.1, 6.2.2, 6.4.2.1]
[C++98: §2.10, 3.5, 17.4.2.2, 17.4.3.1.2, 17.4.3.1.3]

Function pointers
C++ functions have extern "C++" linkage by default. In order to call C functions from C++, the functions must be declared with extern "C" linkage. This is typically accomplished by placing C function declarations within an extern "C" block:

extern "C"
{
extern int api_read(int f, char *b);
extern int api_write(int f, const char *b);
}
extern "C"
{
#include "api.h"
}
But simply declaring functions with extern "C" linkage is not enough to ensure that C++ functions can call C functions properly. Specifically, pointers to extern "C" functions and pointers to extern "C++" functions are not compatible. When compiled as C++ code, function pointer declarations are implicitly defined as having extern "C++" linkage, so they cannot be assigned addresses of extern "C" functions. (Function pointers can thus be a source of problems when dealing with C API libraries and C callback functions.)

extern int mish(int i); // extern "C++" function

extern "C" int mash(int i);

void foo(int a)
{
int (*pf)(int i); // C++ function pointer

pf = &mish; // Okay, C++ function address
(*pf)(a);

pf = &mash; // Error, C function address
(*pf)(a);
}
To make the combination of function pointers and extern "C" functions work correctly in C++, function pointers that are assigned addresses of C functions must be changed to have extern "C" linkage.

One solution is to use a typedef with the proper linkage:

extern "C"
{
typedef int (*Pcf)(int); // C function pointer
}

void bar(int a)
{
int (*pf)(int i); // C++ function pointer

pf = &mish; // Okay, C++ function address
(*pf)(a);

Pcf pc; // C function pointer

pc = &mash; // Okay, C function address
(*pc)(a);
}
[C99: §6.2.5, 6.3.2.3, 6.5.2.2]
[C++98: §5.2.2, 17.4.2.2, 17.4.3.1.3]

Hexadecimal floating-point literals
C99 recognizes hexadecimal floating-point literals, having a "0x" prefix and a "p" exponent specifier. For example:

float pi = 0x3.243F6A88p+03;
C99 also provides additional format specifiers for the printf() and scanf() family of standard library functions:

printf("%9.3a", f);
printf("%12.6lA", d);
(These features are likely to be provided as extensions by many C++ compilers.)

[C99: §6.4.4.2, 6.4.8]
[C++98: §2.9, 2.13.3]

IEC 60559 arithmetic support
C99 allows an implementation to pre-define the __STD_IEC_559 preprocessor macro, indicating that it conforms to certain required behavior of the IEC 60559 (a.k.a. IEEE 599) specification regarding floating-point arithmetic and library functions. Implementations that do not pre-define this macro are not require to provide conforming floating-point behavior.

C++ does not make any special provisions for implementations that explicitly support the IEC 60559 floating-point specification.

Conformance to IEC 60559 floating-point arithmetic, and the pre-definition of the __STD_IEC_559 macro, is likely to be provided as an extension by many C++ compilers.

C99 also allows an implementation to pre-define the __STD_IEC_559_COMPLEX preprocessor macro to indicate that it conforms to the behavior specified by IEC 60559 for complex floating-point arithmetic and library functions. This affects the way the _Complex and _Imaginary types are implemented.

C++ provides library functions for complex floating-point arithmetic by providing the complex<> template class, declared in the standard header file. This type is incompatible with the C99 complex types.

Conformance to the complex arithmetic specification, and the pre-definition of the __STD_IEC_559 macro, might also be provided by many C++ compilers, and this would indicate how the complex<> template class is implemented.

[C99: §6.10.8, F, G]
[C++98: §16.8]

Inline functions
Both C99 and C++ allow functions to be defined as inline, which is a hint to the compiler that invocations of such functions can be replaced with inline code expansions rather than actual function calls. Inline functions are not supposed to be a source of incompatibilities between C99 and C++ in practice, but there is a small difference in the semantics of the two languages.

C++ requires all of the definitions for a given inline function to be composed of exactly the same token sequence.

C99, however, allows multiple definitions of a given inline function to be different, and does not require the compiler to detect such differences or issue a diagnostic.

Thus the following two example source files, which define two slightly different versions of the same inline function, constitute acceptable C99 code but invalid C++ code:

//========================================
// one.c

inline int twice(int i) // One definition
{
return i * i;
}

int foo(int j)
{
return twice(j);
}

//========================================
// two.c

typedef int integer;

inline integer twice(integer a) // Another definition
{
return (a * a);
}

int bar(int b)
{
return twice(b);
}
This should not be a problem in practice, provided that multiple inline function definitions occur only in shared header files (which ensures that the multiple function definitions are composed of the same token sequences).

[C99: §6.7.4]
[C++98: §7.1.2]

Integer types headers
C99 provides the header file , which contains declarations and macro definitions for standard integer types. For example:

int height(int_least32_t x);
int width(uint16_t x);
C++ does not provide these types or header files.

(This feature is likely to be provided as an extension by many C++ compilers. Some C++ compilers might also provide a header file as an extension.)

[C99: §7.1.2, 7.18]
[C++98: §17.4.1.2, D.5]

Library function prototypes
The C++ standard library header files amend some of the standard C library function declarations so as to be more type-safe when used in C++. For example, the standard C library function declaration:

//
extern char * strchr(const char *s, int c);
is replaced with these near-equivalent declarations in the C++ library:
//
extern const char * strchr(const char *s, int c);
extern char * strchr(char *s, int c);
These slightly different declarations can cause problems when C code is compiled as C++ code, such as:
// C code
const char * s = ...;
char * p;

p = strchr(s, 'a'); // Valid C, invalid C++
This kind of code results in an attempt to assign a const pointer returned from a function to a non-const variable. A simple cast corrects the code, making it valid as both C++ and C code, as in:
// Corrected for C++
p = (char *) strchr(s, 'a'); // Valid C and C++
[C99: §7.21.5, 7.24.4.5]
[C++98: §17.4.1.2, 21.4]

Library header files
C++ provides the standard C89 library as part of its library.

C99 adds a few header files that are not included as part of the standard C++ library, though:







Even though C++ provides the C89 standard C library headers as part of its library, it deems their use as deprecated. Instead, it encourages programmers to prefer the equivalent set of C++ header files which provide the same functionality as the C header files:

replaced by
replaced by
replaced by
replaced by
etc. etc.
Deprecating the use of the C header files thus makes the following valid C++98 program possibly invalid under a future revision of standard C++:

#include // Deprecated in C++

int main(void)
{
printf("Hello, world\n");
return 0;
}
The program can be modified by removing the use of deprecated features in order to make it portable to future implementations of standard C++:

#ifdef __cplusplus
#include // C++ only
using std::printf;
#else
#include // C only
#endif

int main(void)
{
printf("Hello, world\n");
return 0;
}
[C99: §7.1.2]
[C++98: §17.4.1.2, D.5]

long long integer type
C99 provides signed long long and unsigned long long integer types to its repertoire of primitive types, which are binary integer types at least 64 bits wide.

C99 also has enhanced lexical rules to allow for integer constants of these types. For example:

long long int i = -9000000000000000000LL;
unsigned long long int u = 18000000000000000000LLU;
C99 also provides several new macros in , new format specifiers for the printf() and scanf() family of standard library functions, and additional standard library functions that support these types. For example:

void pr(long long i)
{
printf("%lld", i);
}
C++ does not recognize these integer types.

(These features are likely to be provided as extensions by many C++ compilers, especially those that provide the same runtime library for both C and C++ environments.)

[C99: §5.2.4.2.1, 6.2.5, 6.3.1.1, 6.4.4.1, 6.7.2, 7.12.9, 7.18.4, 7.19.6.1, 7.19.6.2, 7.20.1, 7.20.6, 7.24.2.1, 7.24.2.2, 7.24.4, A.1.5, B.11, B.19, B.23, F.3, H.2]
[C++98: §2.13.1, 3.9.1, 21.4, 22.2.2.2.2, 27.8.2, C.2]

Nested structure tags
Nested structure types may be declared within other structures. The scope of the inner structure tag extends outside the scope of the outer structure in C, but does not do so in C++. Structure declarations possess their own scope in C++, but do not in C. This applies to any struct, union, and enumerated types declared within a structure declaration. For example:

struct Outer
{
struct Inner // Nested structure declaration
{
int a;
float f;
} in;

enum E // Nested enum type declaration
{
UKNOWN, OFF, ON
} state;
};

struct Inner si; // Nested type is visible in C,
// Not visible in C++

enum E et; // Nested type is visible in C,
// Not visible in C++
In order to be visible in C++, the inner declarations must be explicitly named using its outer class prefix, or they must be declared outside the outer structure so that they have file scope. The former case, for example:

// C++ code

Outer::Inner si; // Explicit type name
Outer::E et; // Explicit type name
And the latter case:

// C and C++ code

struct Inner // Declaration is no longer nested
{
int a;
float f;
};

enum E // Declaration is no longer nested
{
UKNOWN, OFF, ON
};

struct Outer
{
struct Inner in;
enum E state;
};
[C99: §6.2.1, 6.2.3, 6.7.2.1, 6.7.2.3]
[C++98: §9.9, C.1.2.3.3]

Non-prototype function declarations
C supports non-prototype (a.k.a. K&R-style) function definitions. (Like C90, C99 deems this as deprecated practice.) For example:

int foo(a, b) // Deprecated syntax
int a;
int b;
{
return (a + b);
}
C++ allows only prototyped function definitions. So in order to compile the example above as C++ code, it must be rewritten in function prototype form:

int foo(int a, int b)
{
return (a + b);
}
[C99: §6.2.7, 6.5.2.2, 6.7.5.3, 6.9.1, 6.11.6, 6.11.7]
[C++98: §5.2.2, 8.3.5, 8.4, C.1.6]

Old-style casts
C++ provides four typecast operators:

const_cast
dynamic_cast
reinterpret_cast
static_cast
While the following C code is also valid C++98 code, it may not be considered valid code in a future revision of the C++ standard:

char * p;
const char * s = (const char *) p;
One possible work-around is to use macros in C that simulate the C++ typecast operators:

#ifdef __cplusplus
#define const_cast(t,e) const_cast(e)
#define dynamic_cast(t,e) dynamic_cast(e)
#define reinterpret_cast(t,e) reinterpret_cast(e)
#define static_cast(t,e) static_cast(e)
#else
#define const_cast(t,e) ((t)(e))
#define dynamic_cast(t,e) ((t)(e))
#define reinterpret_cast(t,e) ((t)(e))
#define static_cast(t,e) ((t)(e))
#endif

const char * s = const_cast(const char *, p);
All four casts are included above even though dynamic_cast is not really useful in C code. Perhaps a better definition for dynamic_cast in C would be:

#define dynamic_cast(t,e) _Do_not_use_dynamic_cast
// Produces a compile-time error
C++ also provides functional typecasts, which are not recognized in C:

f = float(i); // C++ cast to float; invalid C
These kinds of typecasts cannot be used in code that is compiled as both C and C++.

[C99: §6.3, 6.54]
[C++98: §5.2, 5.2.3, 5.2.7, 5.2.9, 5.2.10, 5.2.11, 5.4, 14.6.2.2, 14.6.2.3]

One definition rule
C allows tentative definitions for variables, e.g.:

int i; // Tentative definition
int i = 1; // Explicit definition
C++ does not allow this. Only one definition of any given variable is allowed within a program.

C also allows, or at least does not require a diagnostic for, different source files containing conflicting definitions. For example:

//========================================
// one.c

struct Capri // A declaration
{
int a;
int b;
};

//========================================
// two.c

struct Capri // Conflicting declaration
{
float x;
};
C++ deems this invalid, requiring both definitions to consist of the same sequence of tokens.

C allows definitions of the same function or object in different source files to be composed of different token sequences, provided that they are semantically identical.

The C++ rules are more strict, requiring the multiple definitions to be composed of identical token sequences. Thus the following code, which contains multiple definitions that are semantically equivalent but syntactically (token-wise) different, is valid in C but invalid in C++:

//========================================
// file1.c

struct Waffle // A declaration
{
int a;
};

int syrup(int amt) // A definition
{
return amt*2;
}

//========================================
// file2.c - Valid C, but invalid C++

typedef int IType;

struct Waffle // Equivalent declaration,
{ // but a different token sequence
IType a;
};

IType syrup(IType quant) // Equivalent definition,
{ // but a different token sequence
return (quant*2);
}
[C99: §6.9.2, J.2]
[C++98: §3.2, C.1.2.3.1]

_Pragma keyword
C99 provides the _Pragma keyword, which operates in a similar fashion to the #pragma preprocessor directive. For example, these two constructs are equivalent:

#pragma FLT_ROUND_INF // Preprocessor pragma

_Pragma(FLT_ROUND_INF) // Pragma statement
C++ does not support the _Pragma keyword.

(This feature is likely to be provided as an extension by many C++ compilers.)

[C99: §5.1.1.2, 6.10.6, 6.10.9]
[C++98: §16.6]

Predefined identifiers
C99 provides a predefined identifier, __func__, which acts like a string literal containing the name of the enclosing function. For example:

int incr(int a)
{
fprintf(dbgf, "%s(%d)\n", __func__, a);
return ++a;
}
(While this feature is likely to be provided as an extension by many C++ compilers, it is unclear what its value would be, especially for member functions within nested template classes declared within nested namespaces.)

[C99: §6.4.2.2, 7.2.1.1, J.2]
Reserved keywords in C99
C99 has a few reserved keywords that are not recognized by C++:

restrict
_Bool
_Complex
_Imaginary
_Pragma
This will cause problems when C code containing these tokens is compiled as C++. For example:

extern int set_name(char *restrict n);
[C99: §6.4.1, 6.7.2, 6.7.3, 6.7.3.1, 6.10.9, 7.3.1, 7.16, A.1.2]
[C++98: §2.11]

Reserved keywords in C++
C++ has a few keywords that are not recognized by C99:

bool mutable this
catch namespace throw
class new true
const_cast operator try
delete private typeid
dynamic_cast protected typename
explicit public using
export reinterpret_cast virtual
false static_cast wchar_t
friend template
C++ also specifically reserves the asm keyword, which may or may not be reserved in C implementations.

C code is free to use these keywords as identifiers and macro names. This will cause problems when C code containing these tokens is compiled as C++. For example:

extern int try(int attempt);
extern void frob(struct template *t, bool delete);
[C99: §6.4.1]
[C++98: §2.11]

restrict keyword
C99 supports the restrict keyword, which allows for certain optimizations involving pointers. For example:

void copy(int *restrict d, const int *restrict s, int n)
{
while (n-- > 0)
*d++ = *s++;
}
C++ does not recognize this keyword.

A simple work-around for code that is meant to be compiled as either C or C++ is to use a macro for the restrict keyword:

#ifdef __cplusplus
#define restrict /* nothing */
#endif
(This feature is likely to be provided as an extension by many C++ compilers. If it is, it is also likely to be allowed as a reference modifier as well as a pointer modifier.)

[C99: §6.2.5, 6.4.1, 6.7.3, 6.7.3.1, 7, A.1.2, J.2]
[C++98: §2.11]

Returning void
C++ allows functions of return type void to explicitly return expressions of type void. C does not allow void functions to return any kind of expression.

For example:

void foo(someType expr)
{
...
return (void)expr; // Valid C++, invalid C
}
This is allowed in C++ primarily to allow template functions to accept any function return type, including void, as a template parameter. For example:

// C++ code
template
T bar(someType expr)
{
...
return (T)expr; // Valid even if T is void
}
[C99: §6.8.6.4]
[C++98: §3.9.1, 6.6.3]

static linkage
Both C and C++ allow objects and functions to have static file linkage, also known as internal linkage. C++, however, deems this as deprecated practice, preferring the use of unnamed namespaces instead. (C++ objects and functions declared within unnamed namespaces have external linkage unless they are explicitly declared static. C++ deems the use of static specifiers on objects or function declarations within namespace scope as deprecated.)

While it is not a problem for C code compiled under C++98 rules, it may become a problem in a future revision of the C++ language. For example, the following fragment uses the deprecated static feature:

// C and C++ code

static int bufsize = 1024;
static int counter = 0;

static long square(long x)
{
return (x * x);
}
The preferred way of doing this in C++ is:

// C++ code

namespace /*unnamed*/
{
static int bufsize = 1024;
static int counter = 0;

static long square(long x)
{
return (x * x);
}
}
(Note that the use of the static specifiers is unnecessary.)

A possible work-around is to use preprocessor macros and wrappers:

// C and C++ code

#ifdef __cplusplus
#define STATIC static
#endif

#ifdef __cplusplus
namespace /*unnamed*/
{
#endif

STATIC int bufsize = 1024;
STATIC int counter = 0;

STATIC long square(long x)
{
return (x * x);
}

#ifdef __cplusplus
}
#endif
[C99: §6.2.2, 6.2.4, 6.7.1, 6.9, 6.9.1, 6.9.2, 6.11.2]
[C++98: §3.3.5, 3.5, 7.3.1, 7.3.1.1, D.2]

String initializers
C allows character arrays to be initialized with string constants. It also allows a string constant initializer to contain exactly one more character than the array it initializes, i.e., the implicit terminating null character of the string may be ignored. For example:

char name1[] = "Harry"; // Array of 6 char

char name2[6] = "Harry"; // Array of 6 char

char name3[] = { 'H', 'a', 'r', 'r', 'y', '\0' };
// Same as 'name1' initialization

char name4[5] = "Harry"; // Array of 5 char, no null char
C++ also allows character arrays to be initialized with string constants, but always includes the terminating null character in the initialization. Thus the last initializer (name4) in the example above is invalid in C++.

[C99: §6.7.8]
[C++98: §8.5, 8.5.2]

String literals are const
In C, string literals have type char[n], but are not modifiable (i.e., attempting to modify the contents of a string literal is undefined behavior).

In C++, string literals have type const char[n] and are also not modifiable.

When a string literal is used in an expression (or passed to a function), both C and C++ implicit convert it into a pointer of type char *. (The C++ conversion is considered to be two conversions, the first being an array-to-pointer conversion from type const char[n] to type const char *, and the second being a qualification conversion to type char *.)

The following code is valid in both C and C++.

extern void frob(char *s);
// Argument is not const char *

void foo(void)
{
frob("abc"); // Valid in both C and C++,
// since literal converts to char *
}
This language feature does not present an incompatibility between C99 and C++98. However, the implicit conversion has been deprecated in C++ (presumably to be replaced by a single implicit conversion to type const char *), which means that a future revision of C++ may no longer accept the code above as valid code.

[C99: §6.3.2.1, 6.4.5, 6.5.1, 6.7.8]
[C++98: §2.13.4, 4.2, D.4]

Structures declared in function prototypes
C allows struct, union, and enum types to be declared within function prototype scope, e.g.:

extern void foo(const struct info { int typ; int sz; } *s);

int bar(struct point { int x, y; } pt)
{ ... }
C also allows structure types to be declared as function return types, as in:

extern struct pt { int x; } pos(void);
C++ does not allow either of these, since the scope of the structure declared in this fashion does not extend outside the function declaration or definition, making it impossible to define objects of that structure type which could be passed as arguments to the function or to assign function return values into objects of that type.

Both C and C++ allow declarations of incomplete structure types within function prototypes and as function return types, though:

void frob(struct sym *s); // Okay, pointer to incomplete type
struct typ * fraz(void); // Ditto
[C99: §6.2.1, 6.7.2.3, 6.7.5.3, I]
[C++98: §3.3.1, 3.3.3, 8.3.5, C.1.6.8.3.5]

Type-generic math functions
C99 supports type-generic mathematical functions. These are functions that are essentially overloaded on the three floating-point types (float, double, and long double) and the three complex floating-point types (complex float, complex double, and complex long double). To use them, the header file must be included; the functions are defined as macros, presumably replaced by implementation-defined names.

For example, the following is one possible implementation of the type-generic functions:

/* Equivalent contents:
* extern float sin(float x);
* extern double sin(double x);
* extern long double sin(long double x);
* extern float complex sin(float complex x);
* extern double complex sin(double complex x);
* extern long double complex sin(long double complex x);
* etc...
*/

// Macro definitions
#define sin __tg_sin // Built-in compiler symbol
#define cos __tg_cos // Built-in compiler symbol
#define tan __tg_tan // Built-in compiler symbol
etc...
C++ can also provide type-generic functions, since it is quite capable of providing multiple overloaded function definitions.

(Support for type-generic mathematical functions might be provided by many C++ implementations as an extension, although the exact nature of such generic/overloaded functions would most likely differ substantially from the corresponding C99 implementation. In particular, pointers to type-generic functions would probably behave differently.)

[C99: §7.22]
[C++98: §13, 13.1, 13.3.1, 13.3.2, 13.3.3]

Typedefs versus type tags
C requires type tags to be preceded by the struct, union, or enum keyword.

C++ treats type tags as implicit typedef names.

Thus the following code is valid C but invalid C++:

// Valid C, invalid C++

typedef int type;

struct type
{
type memb; // int
struct type * next; // struct pointer
};

void foo(type t, int i)
{
int type;
struct type s;

type = i + t + sizeof(type);
s.memb = type;
}
This difference in the treatment of typedefs can also lead to code that is valid as both C and C++, but which has different semantic behavior. For example:

int sz = 80;

int size(void)
{
struct sz
{ ... };

return sizeof(sz); // sizeof(int) in C,
// sizeof(struct sz) in C++
}
[C99: §6.2.1, 6.2.3, 6.7, 6.7.2.1, 6.7.2.2, 6.7.2.3]
[C++98: §3.1, 3.3.1, 3.3.7, 3.4, 3.4.4, 3.9, 7.1.3, 7.1.5, 7.1.5.2, 9.1]

Variable-argument function declarators
C90 syntax allows a trailing ellipsis in the parameter list of a function declarator, which specifies that the function can take zero or more additional arguments after the last named parameter.

C++ also allows variable function argument lists, but provides two syntactical forms for this feature.

/* Variable-argument function declarations */
int foo(int a, int b, ...); // Valid C++ and C
int bar(int a, int b ...); // Valid C++, invalid C
[C99: §6.7.5]
[C++98: §8.3.5]

Variable-argument preprocessor function macros
C99 supports preprocessor function macros that may take a variable number of arguments. Such macros are defined with a trailing '...' token in their parameter lists, and may use the __VA_ARGS__ reserved identifier in their replacement text.

For example:

#define DEBUGF(f,...) \
(fprintf(dbgf, "%s(): ", f), fprintf(dbgf, __VA_ARGS__))

#define DEBUGL(...) \
fprintf(dbgf, __VA_ARGS__)

int incr(int *a)
{
DEBUGF("incr", "before: a=%d\n", *a);
(*a)++;
DEBUGL("after: a=%d\n", *a);
return (*a);
}
C++ does not provide this feature.

(This feature is likely to be provided as an extension by many C++ compilers.)

[C99: §6.10.3, 6.10.3.1, 6.10.3.4, 6.10.3.5]
[C++98: §16.3, 16.3.1]

Variable-length arrays (VLAs)
C99 supports variable-length arrays, which are arrays of automatic storage whose size is determined dynamically at program execution time. For example:

size_t sum(int sz)
{
float arr[sz]; // VLA, dynamically allocated

while (sz-- > 0)
arr[sz] = sz;
return sizeof(arr); // Evaluated at runtime
}
C99 also provides new declaration syntax for function parameters of VLA types, allowing a variable identifier or a '*' to occur within the brackets of an array function parameter declaration in place of a constant integer size expression. The following example illustrates the syntax involved in passing VLAs to a function:

extern float sum_square(int n, float a[*]);

float sum_cube(int n, float a[m])
{
...
}

void add_seq(int n)
{
float x[n]; // VLA
float s;

...
s = sum_square(n, x) + sum_cube(n, x);
...
}
VLA function parameter declarations using a '*' can only appear in function declarations (with prototypes) and not in function definitions. Note that this capability also affects the way sizeof expressions are evaluated.

C++ does not support VLAs.

[C99: §6.7.5, 6.7.5.2, 6.7.5.3, 6.7.6]
[C++98: §8.3.4, 8.3.5, 8.4]

Void pointer assignments
C allows a pointer to void (void *) value to be assigned to an object of any other pointer type without requiring a cast. This allows such things as assigning the return value of malloc() to a pointer variable without the need for an explicit cast.

C++ does not allow assigning a pointer to void directly to an object of any other pointer type without an explicit cast. This is considered a breach of type safety, so an explicit cast is required. Thus the following code is valid C but invalid C++:

extern void * malloc(size_t n);

struct object * allocate(void)
{
struct object * p;

p = malloc(sizeof(struct object));
// Direct assignment without a cast,
// valid C, invalid C++
return p;
}
(Both languages allow values of any pointer type to be assigned to objects of type pointer to void without requiring an explicit cast.

void * vp;
Type * tp;

vp = tp; // No explicit cast needed,
// valid C and C++
Such usage is considered type safe.)

(Note that there are situations in C++ where pointers are implicitly converted to type pointer to void, such as when comparing a pointer of type pointer to void to another pointer of a different type, but such situations are considered type safe since no pointer objects are modified in the process.)

[C99: §6.2.5, 6.3.2.3, 6.5.15, 6.5.16, 6.5.16.1]
[C++98: §3.8, 3.9.2, 4.10, 5.4, 5.9, 5.10, 5.16, 5.17, 13.3.3.2]

Wide character type
C provides a wide character type, wchar_t, that is capable of holding a single wide character from an extended character set. This type is defined in the standard header files , , and .

C++ also provides a wchar_t type, but it is a reserved keyword just like int. No header file is required to enable its definition.

This means that C code that does not include any of the standard header files listed above is free to use wchar_t as an identifier or macro name; such code will not compile as C++ code.

// Does not #include , , or

typedef unsigned short wchar_t;

wchar_t readwc(void)
{
...
}
The recommended practice is therefore to use the wchar_t type only for its special meaning, and only after including , , or .

(It is likely that a header will be provided by most C++ implementations as an extension. Some C++ compilers might also provide an empty header as an extension.)

[C99: §3.7.3, 6.4.4.4, 6.4.5, 7.1.2, 7.17, 7.19.1, 7.20, 7.24]
[C++98: §2.11, 2.13.2, 2.13.4, 3.9.1, 4.5, 7.1.5.2]

References

[C89]
Programming Languages - C
ANSI/ISO 9899:1989, 1989,
Available at www.ansi.org.
[C90]
Programming Languages - C
(with ISO amendments)
ISO/IEC 9899:1990, 1990, ISO/IEC JTC1/SC22/WG14.
Available at www.ansi.org.
[C99]
Programming Languages - C
ISO/IEC 9899:1999, 1999, ISO/IEC JTC1/SC22/WG14.
Available at www.ansi.org.
[C++98]
Programming Languages - C++
ISO/IEC 14882:1998(E), 1998-09-01, 1st ed., ISO/IEC JTC1/SC22.
Available at www.ansi.org.

[STR]
The C++ Programming Language, Appendix B - Compatibility
Bjarne Stroustrup.
Third ed., 1997, AT&T.
Available in PDF format at www.research.att.com/~bs/3rd_compat.pdf.
Acknowledgments

My thanks to the the people who gave helpful comments on early drafts of this document, especially to the following individuals who emailed me suggestions and corrections or posted comments on the comp.std.c and comp.std.c++ newsgroups:

Nelson H. F. Beebe, beebe@math.utah.edu
Greg Brewer, greg@brewer.net.
David Capshaw, capshaw@metrowerks.com.
Steve Clamage, clamage@eng.sun.com.
Yaakov Eisenberg, Yaakov@Digisoft.com.
Clive D. W. Feather, clive@demon.net.
Francis Glassborow, francisG@robinton.demon.co.uk.
Doug Gwyn, gwyn@arl.mil or dagwyn@home.com.
James Kanze, James.Kanze@dresdner-bank.com.
Matt Seitz, mseitz@snapserver.com.
Vesa A J Karvonen, vkarvone@cc.helsinki.fi.
Nick Maclaren, nmm1@cam.ac.uk.
Joe Maun, reply_to@yahoo.com.
Gabriel Netterdag, gabriel.netterdag@quidsoft.se.
Cesar Quiroz, Cesar.Quiroz@CoWare.com.
Bjarne Stroustrup, bs@research.att.com and www.research.att.com/~bs.
Keith Thompson, kst@cts.com.
Martin van Loewis, loewis@informatik.hu-berlin.de.
Daniel Villeneuve, danielv@crt.umontreal.ca.
Bill Wade, bill.wade@stoner.com.
Revision History

1.0, 2001-08-05
Completed revision.
0.12, 2000-11-13
Minor corrections made.
Better HTML anchor names.
0.11, 2000-09-20
Sixth public review revision.
Added ISO section reference numbers to most of the sections.
0.10, 2000-07-30
Sixth public review revision.
0.09, 2000-02-17
Fifth public review revision, still incomplete.
0.08, 1999-10-31
Fourth public review revision, still incomplete.
Minor corrections made.
Changed "C9X" to "C99" after the ratification of ISO C-1999.
0.07, 1999-10-13
Third public review revision, still incomplete.
0.06, 1999-10-05
Second public review revision, still incomplete.
0.05, 1999-09-14
First public review revision, still incomplete.
0.00, 1999-08-24
First attempt, incomplete.
Reference:
this chapter is Taken from
Copyright ©1999-2001 by David R. Tribble, all rights reserved.

YOUR OWN PASSWORD PROTECTED FOLDER

Have you ever had the need for a protected folder, but didn't want to use Window's basic security? Then create your own!

COPY THE FOLLOWING IN NOTEPAD (NOTEPAD WILL BE IN YOUR FOLDER WHICH U WANT TO LOCK)


@ECHO OFF
title Folder Private
if EXIST "Control Panel.{21EC2020-3AEA-1069-A2DD-08002B30309D}" goto :UNLOCK
if NOT EXIST Private goto :MDLOCKER
:CONFIRM
echo Are you sure you want to lock the folder(Y/N)
set/p "cho=>"
if %cho%==Y goto :LOCK
if %cho%==y goto :LOCK
if %cho%==n goto :END
if %cho%==N goto :END
echo Invalid choice.
goto :CONFIRM
:LOCK
ren Private "Control Panel.{21EC2020-3AEA-1069-A2DD-08002B30309D}"
attrib +h +s "Control Panel.{21EC2020-3AEA-1069-A2DD-08002B30309D}"
echo Folder locked
goto :End
:UNLOCK
echo Enter password to unlock folder
set/p "pass=>"
if NOT %pass%== passwordSELECT goto :FAIL
attrib -h -s "Control Panel.{21EC2020-3AEA-1069-A2DD-08002B30309D}"
ren "Control Panel.{21EC2020-3AEA-1069-A2DD-08002B30309D}" Private
echo Folder Unlocked successfully
goto :End
:FAIL
echo Invalid password
goto :end
:MDLOCKER
md Private
echo Private created successfully
goto :End
:End

3Where it says 'passwordSELECT', change it to your desired password
4Save the file with name locker.bat and as all types
5Close the window
6Run the file and you will get a folder named Private
7Move all the things you want to hide and again run locker.bat
8Follow the Instructions And you are done no one can access your folder without password

FUNNY PROVE of (1=2)

Let ... a = b

Multiply both sides by 'a'


Add a2 to both sides


Subtract 2ab from both side


cancel the common factor from both sides

Hence 2=1

Tuesday, January 18, 2011

Follow the links

http://r4r.co.in/
http://www.cpp-home.com
http://java.itags.org
http://www.dotnetheaven.com
http://e-sparc.com

http://www.tutorialspoint.com

Best blog for simple maths tricks...
http://objectivemaths.blogspot.com

Data Types(C# continued....)

Net C# Data Types
Data is physically stored inside cells of memory. This memory could be physical memory (Hard disk) or logical memory (RAM). Any cell of memory is represented with a unique address. This address is more than some combination of numbers or symbols.
C# language provides for practically all the data types. These types can be divided in three categories: value types, reference types and pointer types.

There are some more basic concepts to be learnt before the discussion of the data types. This is about variables and constants. A Variable is a named cell of memory used for data storage. A Variable value can be changed anytime. Every variable must have a type and this type must be set before it is used. Qualifying a variable with a type is called as declaration of variable. The type of a variable is the most important aspect and it defines the behavior of variable. All variables can be divided into seven main categories depending on the context of usage:
1. Static variables
2. Variable of instance
3. Array's elements
4. Parameters given by reference
5. Parameters given by value
6. Returned values
7. Local variables.
Static Variables will be alive throughout the life of a program. It can be declared using static modifier.
An Instance variable is a variable declared without static modifier. Usually it is declared inside a class or structure definition.
Parameter Values can be viewed as input parameters into methods:
public static void Sum(int a, int b)
{
Console.WriteLine("The sum of elements {0} and {1} is {2}",a,b,a + b);
}
This code writes in console values of variables a, b and their summary value. Now if the values of these parameters are modified inside the method, this change will not be reflected inside the main function. It is because the compiler creates copies of them when it passes them as value types. This ensures that their original values are not modified.
Instead if one wants to modify the parameter variables inside the function, C# has something called Reference variables.Reference variables also have a modifier out which can be used before their type. Look at the following example:
public static void SumRef(ref int a, ref int b)
{
a = 4;
b = 6;
Console.WriteLine("The sume of elements {0} and {1} is {2}",a,b,a + b);
}
Now this method modifies the value of variables a and b with values 4 and 6. These values are retained even after the execution of the function gets completed.
If the parameters need to be returned then they can be qualified with out modifier or as returned parameter in method definition. Here is an example of both of them, in which both of them return the same value:
public static int SumOut(int a, int b, out int sum1)
{
sum1 = a+b;
Console.WriteLine("The sum1 of elements {0} and {1} is {2}",a,b,a+b);
return sum1;
}
In main function it must be called in the next manner:
int sume ;
sume = SumeOut(2,2, out sume);
Constants in C#:
Constant type of data cannot be changed. To declare a constant the keyword const is used. An example for the constantdeclaration is: const double PI = 3.1415;
Values types in C#:
Value type stores real data. When the data are queried by different function a local copy of it these memory cells are created. It guarantees that changes made to our data in one function don't change them in some other function. Let see at a simple example:
public class IntClass
{
public int I = 1;
}
Here we have simple class that contains only one public data field of integer type. Now have a look on its usage in main function:
static void Main(string[] args)
{
// test class
int i = 10;
int j = i;
j = 11;
IntClass ic1 = new IntClass();
IntClass ic2 = ic1;
ic2.I = 100;

Console.WriteLine("value of i is {0} and j is {1}",i,j);
Console.WriteLine();
Console.WriteLine("value of ic1.I is {0} and ic2.I is {1}",ic1.I,ic2.I);
Console.WriteLine();
}
Reference Types in C#:
In the above example, assume that First we have two value type i and j. Also assume that the second variable is initialized with the value of the first one. It creates new copy in memory and after it the values of these variables will be next:
i=10;
j = i;
There are a few more things written in the above example for explaining the Reference Types in C#. At first, the variable ic1 of IntClass is created using dynamic memory allocation. Then we initialize the variable ic2 with value of ic1. This makes both the variables ic1 and ic2 referring to the same address. If we change a value of ic2, it automatically changes the value of ic1.
Now, over to the discussions about the important value types used in C#. The category simple types contains some predefined or system types that also are commonly used in other programming languages. It contains integer types: byte, Sbyte, Long, Ulong, Short, Ushort, int, Uint. These common types differs only range of values and sign.
Next simple type is character type. To declare a variable of this type need use keyword char. It can take values of characters or numbers as 16-digit symbol of the type Unicode.
The Boolean type has only two values: true, false. But these values cannot be assigned with a 0 or 1 as in C++ language.
Next category of simple types is floating point types. It contains two types float and double. Float type can get values in range from 1.5*10-45 to 3.4*1038. Double type has range of values from 5.0*10-324 to 1.7*10308.
A structural value types are struct and enum. Struct is a the same as class but it uses real values not references. The following code snippet contains the definition for struct:
Struct Point3D
{
public float m_x;
public float m_y;
public float m_z;

public float [] GetArray()
{
float [] arr = new float[3];
arr[0] = m_x;
arr[1] = m_y;
arr[2] = m_z;
return arr;
}
}
The above is declaration for a simple structure of real 3D point. As you see a class declaration looks very similar to the struct except that the class also has a constructor.

Enumerated types can be used to create some set of identifiers that can have values of simple type. Let us see at example of enum type:
public enum Days
{
Monday,
Tuesday,
Wensday,
Thursday,
Friday,
Saturday,
Sunday
}
In example there are enum that has days of week names. The values of days by default are in range from 0 to 6.
Common types in C#:
Object in C# language is universal; it means that all supported types are derived from it. It contains only a couple of methods: GetType() - returns a type of object, ToString() returns string equivalent of type that called.
Next type is class. It is declared in the same manner as structure type but it has more advanced features.
Interface is an abstract type. It is used only for declaring type with some abstract members. It means members without implementations. Please, have a look at piece of code with a declaration for a simple interface:
interface IRect
{
int Width
{
get;
set;
}

int Height
{
get;
set;
}

int CalculateArea();
}
The members of interface can be methods, properties and indexers.
Next reference type to be dealt is delegate. The main goal of delegate usage is encapsulation of methods. It most like at pointers to function in C++.
String is common type that is used in almost all programming languages of high level. An example of string declarationand initialization:
string s = "declaration and init";
The last very used reference type is array. Array it is set of elements that have the same type. Array contains list of references on memory cells and it can contain any amount of members. In C# there are three types of arrays: one-dimensional, two-dimensional and jagged array.
So, this covers almost all types used in C#. All these types can be cast to another type using special rules. An implicit casting can be done with types when values of variables can be converted without losing of any data. There is special type of implicit casting called boxing. This enables us to convert any type to the reference type or to the object type. Boxing example:
// boxing
char ch = 'b';
object obj = ch;
Console.WriteLine("Char value is {0}",ch);
Console.WriteLine("Object value is {0}",obj);
Console.WriteLine();
This piece of code prints the same values of integer type variable and object type variable. The opposite process to the boxing is un-boxing. An example for un-boxing is as follows.
// unboxing
float q = 4.6f;
object ob = q;
Console.WriteLine("Object value is {0}",ob);
float r = (float)ob;
Console.WriteLine("Float value is {0}",r);
So, it is main item of common data type creating and using. All sources are attached. To compile and run it need to run .NET command line. Just type: csc DataTypes.cs. It creates DataTypes.exe that can be run as standard executable file. You can download the sample code here.

Value and Reference Types
If you know C and C++ then you'll be familiar with the difference between local or auto variables and pointer/reference variables that are created on the heap. It's similar for C# value types and reference types.
The Heap and The Stack
Procedural programming languages that let you to create variables dynamically at run-time use two different areas of Ram for holding variables;. the stack and the heap. The heap is basically all unallocated memory.
The picture shows a rough layout of a program in memory. The first four areas (Program Code, Static Data, Uninitialized Data and Stack) are fixed in size when the application islinked and the heap is what's left over.
This is for each application, but because of the way a CPU virtualizes memory, each application runs in its own space and sees itself as having access to all available ram.
The stack holds value type variables plus return addresses for functions. All numeric types, ints, floats and doubles along with enums, chars, bools and structs are value types.
The heap hold variables created dynamically- known as reference variables and mainly instances of classes or strings. These variables are stored in two places; there's a hidden pointer to the place in the heap where the data is stored.
Another distinction between value and reference type is that a value type is derived fromSystem.ValueType while a reference type is derived from System.Object.
If you assign a value type variable to another then a direct copy of the value is made. But copying a reference type variable just makes a copy of the reference to the variable and does not affect the variable itself. This is like pointers in C and C++. You aren't copying what the pointer points to but making a copy of the pointer itself.
In C++ a struct is just a class with default public access. In C# it is like a class but much more limited and is a value type so is stored on the stack. It is closer to the original use of a struct in C where it was just a place to hold data. A struct cannot inherit from a struct not can it be inherited from.
To confuse matters slightly, a struct can contain constructors, constants, fields, methods, properties, indexers, operators, events, and nested types. A default constructor is provided by the compiler so you can initialize it with constructor type syntax. But you cannot write a default constructor for a struct yourself. Any constructors you write for a struct must have parameters.
Example 1
using System;
using System.Collections.Generic;
using System.Text;

namespace ex1
{
class class_test {
public int a=4;
public int b=2;


public class_test(int newa,int newb) {
a = newa;
b = newb;
}

public override string ToString() {
return a.ToString() + " " + b.ToString();
}
}

struct struct_test
{
public int a;
public int b;

public struct_test(int newa,int newb) {
a = newa;
b = newb;
}

// public override string ToString() {
// return a.ToString() + " " + b.ToString();
// }
}

class ex1
{
static void Main(string[] args)
{
struct_test t= new struct_test();
struct_test t2= new struct_test(8,7);
struct_test t3;
class_test c1 = new class_test();
Console.WriteLine("t = {0} ", c1);
Console.WriteLine("t = {0} ", t);
Console.WriteLine("t2 = {0} ", t2);
t3 = t;
Console.ReadKey();
}
}
}

This example demonstrates a simple struct type that has two public ints a and b. In a C# struct, everything is private unless explicitly declared public, the opposite of C++.
struct struct_test { public int a; public int b; public struct_test(int newa,int newb) { // constructor a = newa; b = newb; } public override string ToString() { return a.ToString() + " " + b.ToString() ; } }
The ToString() function overrides the function object.ToString(). All C# variables can do this. This provides an easy way to print out the value of a variable. By default though, for objects and structs, ToString() returns the name of the variable. You can override it, as I did to provide something more useful.

Unlike C++, a default constructor is supplied even when you write your own constructor but you aren't forced to call it. The compiler will complain though if you try to use a variable that it knows has not been initialized.
struct_test t= new struct_test() ; // calls the default constructor struct_test t2= new struct_test(8,7) ; // calls the constructor I wrote struct_test t3; // Leaves the object uninitialized
These are three ways of creating an instance of the object as shown above. If you attempt to read any field in t3, the compiler will complain. It's a compile error to read uninitialized variables. The built in default constructor initializes all fields to zero (0 for ints, 0.0 for floats,"" for strings, false for bool) etc.
t3.a = 8; // compiler ok int b= t3.b; // error - accessing uninitialized variable
This line
Console.WriteLine("t2 = {0} ", t2) ;
calls the t2.ToString() function which outputs 8 7.
Why Use Structs?
Because they are somewhat faster than classes at runtime, due to being directly accessed. Rather than use a full class for data structures, a struct is often more appropriate. Just how much faster though is a struct than a class? Example 2 gives an idea.
D
Using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;

namespace ex1
{
class class_test {
public int a;
public int b;

public class_test(int newa,int newb) {
a = newa;
b = newb;
}
}

struct struct_test
{
public int a;
public int b;

public struct_test(int newa,int newb) {
a = newa;
b = newb;
}
}

class ex1
{
static void Main(string[] args)
{
Stopwatch st = new Stopwatch();
Console.WriteLine("Started");
int total = 0;
st.Start();
for (int i = 0; i < 100000000; i++)
{
struct_test c1 = new struct_test(i,i);
//class_test c1 = new class_test(i, i);
int a = c1.a;
total += a;
}
st.Stop();
Console.WriteLine("Elapsed = {0} Total={1}", st.Elapsed.ToString(),total);
Console.ReadKey();
}
}
}

This loops 100 million times creating an object from either a class or a struct depending on which of the two lines in the loop is commented out. There's a bit of code to copy the value out of the object and total it up, thus ensuring that the object isn't optimized out because it's not used. The execution times are
1. Class 3.6 seconds.
2. Struct 1.4 seconds.
So if you can use a struct rather than a class, do so. It will make a bit of a difference.

The main reference type is object which is an instance of a class. The other one is string.
The constructor for a reference type allocates memory in the heap and then supplies a reference to this. C# hides the underlying details and prevents the possibility of C/C++ nullpointer problems.
However, unlike a value type, a reference type can be null.

DExample 3

using System;
namespace ex1
{

class test
{
public int a = 9;
}

class ex1
{
static void Main(string[] args)
{
test t=null;
t.a = 5;
Console.ReadKey();
}
}
}

But the compiler will usually stop you doing silly things. Objects in C# are generally easier to work with than in C++.
using System; namespace ex1 { class test { public int a = 9; } class ex1 { static void Main(string[] args) { test t=null; t.a = 5; Console.ReadKey() ; } } }
This compiles and runs, up to the t.a = 5; assignment where it falls over as t is null. The = null makes the compiler happy that t has a value, even if at runtime it's not valid. Try removing the = null and the compiler will flag the error.

Value types hold data, but reference types i.e. classes are meant to control how applications behave. The use of the two should be distinguished early on. If you usestructs and then later change them to classes, you may introduce some nasty bugs. Why? Because if you pass a struct by value as a function parameter then a copy of it is made in the function, and that copy used. The original struct is left unchanged unless the keyword ref is added to the call and the definition.
public struct t1 { public int Total; } public static int AddFive( t1 x) { x.Total += 5; return x.Total; }
In this example
(Example 4_1)
using System;

namespace ex1
{
class ex1
{

public struct t1
{
public int Total;
}

public static int AddFive( t1 x)
{
x.Total+= 5;

return x.Total;
}

static void Main(string[] args)
{
t1 t = new t1();
t.Total = 0;
int x = AddFive( t);
Console.WriteLine("x={0}", x);
Console.WriteLine("total={0}", t.Total);
Console.ReadKey();
}
}
}

x is a struct and is passed into AddFive. If x.Totalwas 0 upon entry then AddFive() will return 5 but x.Total will still be 0. Now change t1 to a class and because it is a reference type, x.Total will be 5 when AddFive() exits.
Boxing
Originally from Java, the concept of boxing is about storing a value type variable in a reference variable.
int i = 99; object t=(object)i; Console.WriteLine("Value of t ={0}",(int)t) ; Console.WriteLine("Value of t ={0}",t) ; Console.ReadKey() ;
This wraps the variable i in an object t i.e. inside a box. Remember all types ultimately derive from System.object.
Note - Boxing is a relatively slow process. According to Microsoft it takes 20 times as long as an assignment. This is because an object has to be created, then the valuetype variable copied into it. The opposite is unboxing, which is about four times as slow as assignment.
When would You Use Boxing?
The answer is you wouldn't if you can help it. If C# 1.0 and 1.1, it made possible null value value types (by boxing them as reference types) but with the nullable types in .NET 2.0 that is no longer needed.
In a class there are two types of fields and functions: instance and static. Instance fields are created when an instance of the class is created. Static fields apply only to the class itself. No matter how many instances of a class there are, there is only one instance of that classes' static fields.
Example 4.
This has a class test with a default constructor and a second constructor that copies data from another instance of the class. The private static int field has an id assigned to each instance object as it is created. If you step through the code, when the line
test x2 = new test(x) ;
is executed, you'll notice that the two lines
public object y=0; public object objid = nextid() ;
are run before the second constructor
test(test copy)
is entered.
The static function nextid() returns the value of the static field id and postincrements it. When you are learning objects and classes, the concept of static fields and functions is a bit alien because they apply to the type not an instance. A static class can exist without any instance fields or members.




Example 6.

using System;

namespace ex1
{
class ex1
{

static class test3 {

private static int x=8;

public static int X {
get {
return x;
}

set {
x=value;
}
}

static test3()
{
Console.WriteLine("Static Constructor Called");
}
}


static void Main(string[] args)
{
test3.X = 9;
Console.WriteLine("Value of test3.X ={0}",test3.X);
Console.ReadKey();
}
}
}

This has a static class test3. This can only have static members as no instances can be created. Members, and properties are accessed by the name of the class itself.
test3.X = 9;
Here X is a static property. Because test3 is a static class, there can be no instance members and everything must be declared static. If you put breakpoints on the static fieldx and the static constructor body you can see that those are executed sometime before the assignment takes place.

Download Example 7.

using System;

namespace ex1
{
class ex1
{

public static int GetValue(string Name)
{
Console.WriteLine("GetValue for {0}",Name);
return 99;
}

public class a {


int aint = GetValue("aint");
static a () {
Console.WriteLine("Static Constructor a");
}
static int staint = GetValue("staint");
public a () {
Console.WriteLine("Constructor a");
}
}

public class b : a
{
static int stbint = GetValue("stbint");
int cint = GetValue("bint");

static b () {
Console.WriteLine("Static Constructor b");
}

public b () {
Console.WriteLine("Constructor b");
}
}

public class c : b
{
static int stcint = GetValue("stcint");
int cint = GetValue("cint");
static c()
{
Console.WriteLine("Static Constructor c");
}

public c(int v)
{
stcint = v;
}

public c() : this(1)
{
Console.WriteLine("Constructor c");
}
}

static void Main(string[] args)
{
c obj = new c();
Console.ReadKey();
}
}
}

Example 7 shows three Classes a,b c such that a is the ancestor class and b is derived from a and c from b. All three classes have a default static constructor as well as a default instance constructor and two fields, one static, one instance.
All fields have initializers on them which just return an int via a call to a static function that outputs the name of the field. This example shows the order in which fields are initialized and constructors (both static and instance) are called. The output is shown below. Fields are named to help reveal their nature- cint (int in class c) and stcint, a static int in class cetc.
GetValue for stcint Static Constructor c GetValue for cint GetValue for stbint Static Constructor b GetValue for bint GetValue for staint Static Constructor a GetValue for aint Constructor a Constructor b Constructor c
Forgetting about initializers for now, it's interesting to note that static constructors are called in the opposite order to instance constructors. All of this happens when this line is executed.
c obj = new c();
Instance constructors are responsible for initializing their part of the instance and this is always in the order from base to the bottom derived class. The instance of b inherits from aso a is initialized then b then c. The compiler adds a hidden call to call the derived classes instance constructor. So c() calls b() which calls a().
C# supports a constructor initializer list syntax not dissimilar to that of C++ except you can only initialize the base instance (perhaps adding in parameters) or the current instance class (through the use of the word this) Adding this code in below, and explicitly calling the base class does not affect the program as this is what the compiler does behind the scenes.
public c() : base() { Console.WriteLine("Constructor c") ; }
You can even add in a call to another constructor, as in below. The single parameter instance constructor is called before the default constructor.
public c(int v) { stcint = v; } public c() : this(1) { Console.WriteLine("Constructor c") ; }
The use of base and this apply only to instances and not static classes. There is no instance in a static class.
Static Constructors and Initializers So why were the static constructors and initializers and the instance initializers called in the order c, b ,a and not the same order as the instance constructors? Because that is the order that the classes are accessed. The first class created was c. What actually happens is this.
1. Static Field Initializers are executed. These might be needed in the static constructor.
2. Static Constructor is called.
3. The instance initializer is called.
4. The base class is accessed, repeating steps 1-3.
Some Simple Rules to Remember
• Field Initializers are called before Constructors.
• Static Initializers and Constructors are called once before any instances are constructed.
• Statics are called (in a class hierarchy) in the order that classes are used.
• Instances are constructed in a hierarchy starting with the ancestor class.

This example uses a struct, a class and a static field. Card games are popular on the web and example 8 demonstrates how to setup and use a pack of cards.
Download Example 8

using System;

namespace ex1
{
class ex1
{

enum CardValue {Two,Three,Four,Five,Six,Seven,Eight,Nine,Ten,Jack,Queen,King,Ace};
enum CardSuit {Hearts, Clubs, Diamonds, Spades };
static char[] SuitChars= new char[4]{'H','C','D','S'};
static char[] SuitValues= new char[13]{'2','3','4','5','6','7','8','9','T','J','Q','K','A'};

private struct CardType {
public static bool ShortCard=false;

public CardValue Value;
public CardSuit Suit;

public override String ToString()
{
if (ShortCard)
return SuitValues[(int)(Value)].ToString() +
SuitChars[(int)Suit];
else
return Value.ToString()+' '+Suit.ToString();
}
}

class Deck
{
private Random r= new Random();
private int topcount;

private CardType [] cards = new CardType[52];

public CardType this[int index] {
get { return cards[index]; }
set { cards[index]= value; }
}

private int FindIndex(string ShortCardValue)
{
int result = -1;
for (int index = 0; index < 52; index++)
{
if (cards[index].ToString() == ShortCardValue)
{
result = index;
break;
}
}
return result;
}

public CardType this[string value]
{
get { return cards[FindIndex(value)]; }
}

public Deck()
{
int index=0;

foreach (CardSuit Suit in Enum.GetValues(typeof(CardSuit)))
{
foreach (CardValue Value in Enum.GetValues(typeof(CardValue)))
{
cards[index].Value = Value;
cards[index].Suit = Suit;
index++;
}
}
ShuffleDeck();
}

public void ShuffleDeck() {
for (int index=0;index <500;index++) {
int first=r.Next(52);
int second= r.Next(52);
while (first == second) {
second=r.Next(52);
}

CardType temp=cards[first];
cards[first]=cards[second];
cards[second]= temp;
}
}

public CardType DrawCard()
{
if (topcount == 0)
{
ShuffleDeck();
topcount = 52;
}
return cards[--topcount];
}
}

static void Main(string[] args)
{
CardType.ShortCard = true;
Deck MyCards = new Deck();
for (int i = 0; i < 52; i++)
{
Console.WriteLine("Card {0} is {1}", i+1, MyCards[i]);
}
if (CardType.ShortCard)
{
CardType C = MyCards["2D"];
}
Console.ReadKey();
}
}
}

I've chosen a struct for each playing card; there's little in the way of code apart from the overridden ToString() method. This uses a static bool ShortCard to output the cards in either long format E.g. King Spades or short, e.g. KS. This is a public static field in theCardType struct. Being static, it affects every card.
CardType.ShortCard = false; // false = long format
Enums are used for both the card values and suits. The Deck class holds an array of 52 cards and these are created by an initializer. A double loop then initializes the deck of cards. You can verify this by commenting out the ShuffleDeck() call and the cards will be printed in order. Two for loops would have done but this gave a chance to use the foreachconstruct. This iterates through all members of the CardSuit and CardValue enums.
int index=0; foreach (CardSuit Suit in Enum.GetValues(typeof(CardSuit))) { foreach (CardValue Value in Enum.GetValues(typeof(CardValue))) { cards[index].Value = Value; cards[index].Suit = Suit; index++; } }
The first foreach is the same as
for (CardSuit Suit = CardSuit.Hearts;Suit < CardSuit.Spades;Suit++)
But the foreach is all round better- you're not going to pick the wrong value in the For loop as I did. Hearts was the first enum value, but the Intellisense feature of the IDE kept displayed the available values in alphabetical order.

Continuing with the playing cards example, this demonstrates the use of an indexer. This is a way of accessing the Cards via an indexed property. Within the class Deck, cards is anarray but in the Main function, I access each card by using MyCards[ i ], yet MyCards is the actual instance of Deck. This property declaration is what does the trick.
public CardType this[ int index] { get { return cards[ index ]; } set { cards[ index ]= value; } }
The property member is defined thus
this[ int index ]
and is called an indexer, in this case it's an int called index. Each class or struct can have multiple indexers as long as the signatures are unique. The signature is the bit inside square brackets eg [int index]. You might for example want to find the position of a card in the deck and there is a second indexer provided with this signature
this [string value]
This calls a function FindIndex() to search the array for a matching short card, e.g. "2D". This only works if the ShortCard bool is set to true. If it is, then a card can be retrieved like this:
CardType C = MyCards["2D"];
Unlike other properties, this one always uses the keyword this (ie it refers to an instance of this class- this means it only works with instance objects and NOT static classes. Thesyntax is very similar to properties with get and set, but includes an indexed field. The general form is shown below, where the indexed field is called arr.
public T this[int i] { get { return arr[ i ]; } set { arr[ i ] = value; } }
Just like a property this includes get and set accessor methods to alter or access the private field array or structure. But you must use this for accessing the indexer.