Category:C: Difference between revisions
m (LCT link) |
m (Fixed syntax highlighting and tidied the examples a bit.) |
||
(47 intermediate revisions by 14 users not shown) | |||
Line 1: | Line 1: | ||
<div class="messagebox">Due to technical limitations, the link [[C sharp|C#]] points to here in some articles. To correct this issue, replace <nowiki>[[C#]] with [[C sharp|C#]]</nowiki>.</div> |
|||
{{language|C |
|||
{{language |
|||
|exec=machine |
|exec=machine |
||
|gc=no |
|gc=no |
||
|safety=unsafe |
|safety=unsafe |
||
|parampass= |
|parampass=value |
||
|checking=static |
|checking=static |
||
|compat=nominative |
|compat=nominative |
||
Line 9: | Line 10: | ||
|strength=weak |
|strength=weak |
||
|tags=c |
|tags=c |
||
|hopl id=577 |
|||
|LCT=yes}}{{language programming paradigm|Imperative}}{{Codepad}}<div class="messagebox">Due to technical limitations, the link [[C sharp|C#]] points to here in some articles. To correct this issue, replace <nowiki>[[C#]] with [[C sharp|C#]]</nowiki>. Additionally, a bug in mod_rewrite causes some C++ links to redirect here. Try [http://rosettacode.org/w/index.php?title=C%2B%2B this link] instead.</div> |
|||
|LCT=yes |
|||
'''C''' is a general-purpose, [[procedural programming|procedural]], [[imperative programming|imperative]] computer programming language developed in 1972 by Dennis Ritchie at the [[Bell Labs|Bell Telephone Laboratories]] for use with the [[UNIX]] operating system. It has since spread to many other [[:Category:Platforms|platforms]], and is now one of the most widely used programming languages. C has also greatly influenced many other popular languages, such as [[C++]] and [[Objective-C]], which were originally designed as enhancements to C. People are so familiar with its syntax that many other languages such as [[AWK]], [[PHP]], [[Java]], [[JavaScript]], [[D]], and [[C Sharp|C#]] deliberately used its "look and feel". C is the most commonly used programming language for writing system software, though it is also widely used for writing applications. [[C]] is the ''lingua franca'' of the [[open source]] community. |
|||
|bnf=http://c.comsci.us/syntax/index.html |
|||
}}{{language programming paradigm|Imperative}}{{Codepad}} |
|||
'''C''' is a general-purpose, [[procedural programming|procedural]], [[imperative programming|imperative]] computer programming language developed in 1972 by Dennis Ritchie at the [[Bell Labs|Bell Telephone Laboratories]] for use with the [[UNIX]] operating system. C evolved from its predecessor, [[derived from::B]]. |
|||
C has since spread to many other [[:Category:Platforms|platforms]], and is now one of the most widely used programming languages. C has also greatly influenced many other popular languages, such as [[C++]] and [[Objective-C]], which were originally designed as enhancements to C. People are so familiar with its syntax that many other languages such as [[AWK]], [[PHP]], [[Java]], [[JavaScript]], [[D]], and [[C Sharp|C#]] deliberately used its "look and feel". C is the most commonly used programming language for writing system software, though it is also widely used for writing applications. [[C]] is the ''lingua franca'' of the [[open source]] community. |
|||
==Versions== |
==Versions== |
||
* '''K&R C''' was the first widely-used form of C. It was originally documented in ''The C Programming Language'', published in 1978. It is named for the authors, Brian Kernighan and Dennis Ritchie (also the language's creator). Code in this style is virtually nonexistent today. |
* '''K&R C''' was the first widely-used form of C. It was originally documented in ''The C Programming Language'', published in 1978. It is named for the authors, Brian Kernighan and Dennis Ritchie (also the language's creator). Code in this style is virtually nonexistent today. |
||
* '''C89''' (often called '''[[ANSI]] C''') is the version of C standardized by ANSI in 1989. It is the most commonly used and supported version of the language |
* '''C89''' (often called '''[[ANSI]] C''') is the version of C standardized by ANSI in 1989. It is the most commonly used and supported version of the language. |
||
* '''C90''' (often called '''[[ISO]] C''') is |
* '''C90''' (often called '''[[ISO]] C''') is identical to C89, republished by ISO in 1990. |
||
* '''C99''' is a significant improvement, adopting many features of [[C++]] and standardizing common compiler extensions. It was standardized by ISO in 1999, and by ANSI in 2000. It is |
* '''C99''' is a significant improvement, adopting many features of [[C++]] and standardizing common compiler extensions. It was standardized by ISO in 1999, and by ANSI in 2000. It is primarily supported by commercial C compilers, but most of its features are available in [[Clang]] [[GCC]]. [http://gcc.gnu.org/c99status.html] |
||
* '''C11''' is the previous standard, published in December 2011. It is the default for [[GCC]] as of version 5.1. |
|||
* '''C18''' is the current standard, published in June 2018. It is the default for [[GCC]] as of version 8.1. |
|||
* '''C2x''' is the upcoming standard, expected to be voted on in 2023 - it will then become C23. [[GCC]] 9, [[Clang]] 9 and Pelles C 11 have preliminary support for it. |
|||
== |
==Overview== |
||
*[[wp:C_%28programming_language%29|Wikipedia:C (programming language)]] |
|||
===Curly Braces=== |
|||
{{language programming paradigm|Imperative}} |
|||
C uses curly braces as a separator for sections of code. All curly braces must be "balanced," i.e. every left curly brace must have a right curly brace after it. Nesting curly brace pairs inside curly braces is also acceptable as long as none of them are "lonely." |
|||
Most advanced code editors will help you with curly braces by automatically typing the right brace as soon as you type the left one. It is a matter of style as to whether you prefer to place an opening curly brace on its own line or at the end of the previous line. Here we use the latter style. |
|||
==BNF Grammar== |
|||
=={{header|C}}== |
|||
<pre> |
|||
! ----------------------------------------------------------------------- |
|||
! ANSI C |
|||
! |
|||
! The C programming language evolved at Bell Labs from a series of |
|||
! programming languages: 'CPL', 'BCPL', and then 'B'. As a result, C's |
|||
! development was a combined effort between Dennis Ritchie, Ken Thompson, |
|||
! and Martin Richards. |
|||
! |
|||
! C was designed for the creation and implementation of low-level systems |
|||
! such as operating systems, device drivers, firmware, etc... To realize |
|||
! this goal, the language contains the ability to perform operations |
|||
! directly on memory and has direct access to system pointers. While this |
|||
! gives an enormous amount of control and flexibility, it also makes C a |
|||
! professional programming language - not to be used by an inexperienced |
|||
! programmer. |
|||
! |
|||
! C (and later C++) quickly became the de facto standard for developing |
|||
! operating systems, applications and most other large projects. UNIX as |
|||
! well as Windows, Linux, and Mac-OS X were developed using this |
|||
! language (and its successors). |
|||
! |
|||
! More information is available at Dennis Ritchie's website: |
|||
! http://cm.bell-labs.com/cm/cs/who/dmr/ |
|||
! |
|||
! The C grammar is inherently ambigious and requires a large number of |
|||
! LALR(1) states to parse. As a result, the time required by the GOLD |
|||
! Parser Builder to compile this grammar is extensive. |
|||
! |
|||
! C is not a line-based grammar with the notable exception of compiler |
|||
! directives (which are preceeded by a '#' character). These are usually not |
|||
! handled directly by the actual parser, but, rather, the pre-processor. |
|||
! Before the program is analyzed by the parser, C compilers scan the code and |
|||
! act on these commands. The final C program is then passed to the parser. |
|||
! ----------------------------------------------------------------------- |
|||
<syntaxhighlight lang="c">int main() { |
|||
! ----------------------------------------------------------------------- |
|||
! This grammar does not contain the compiler directives. |
|||
! |
|||
! Note: This is an ad hoc version of the language. If there are any flaws, |
|||
! please visit the contact page and tell me. |
|||
! |
|||
! SPECIAL THANKS TO: |
|||
! BOB MEAGHER |
|||
! MIKE WISDOM |
|||
! VLADIMIR MOROZOV |
|||
! TOM VAN DIJCK |
|||
! |
|||
! Modified 06/14/2002 |
|||
! * The correct definition for "return" was added. Thanks to Bob Meagher. |
|||
! * Added the missing rules for labels, storage specifications, etc... |
|||
! which were left out. Thanks to Mike Wisdom for calling this to |
|||
! my attention. |
|||
! |
|||
! Modified 06/21/2002 |
|||
! * I fixed an error in the grammar for declaring functions. |
|||
! |
|||
! Modified 06/15/2003 |
|||
! * Vladimir Morozov fixed an error for calling functions with no parameters |
|||
! |
|||
! Modified 01/31/2004 |
|||
! * Tom van Dijck found a bug in the grammar concerning variable |
|||
! initialization. |
|||
! |
|||
! Modified 04/26/2004 |
|||
! * Some errors in the grammar were fixed. |
|||
! |
|||
! Modified 01/19/2005 |
|||
! * The definition for comments was modified. In ANSI C, block comments |
|||
! cannot be nested. As a result, they are defined using the whitespace |
|||
! terminal. |
|||
! |
|||
! Modified 03/28/2007 |
|||
! * The commented-out definition for non-nested comments was updated. The |
|||
! previous version did not work in all cases. |
|||
! ----------------------------------------------------------------------- |
|||
// Your main program goes here. |
|||
// If you forgot either of these curly braces you would get an error message when you try to compile! |
|||
}</syntaxhighlight> |
|||
"Name" = 'ANSI C' |
|||
"Version" = '1973' |
|||
"Author" = 'Dennis Ritchie, Ken Thompson, Martin Richards' |
|||
"About" = 'C is one of the most common, and complex, programming languages in use today.' |
|||
The contents of a function, if statement, etc. <b>must</b> be enclosed in curly braces for the code to count as part of that section. |
|||
"Case Sensitive" = True |
|||
<syntaxhighlight lang="c">{ |
|||
"Start Symbol" = <Decls> |
|||
// This wouldn't actually compile as none of these variables were declared in this scope. More on that later. |
|||
if (K == 3) { |
|||
{Hex Digit} = {Digit} + [abcdefABCDEF] |
|||
X = Y; // This line will be skipped if K doesn't equal 3. |
|||
{Oct Digit} = [01234567] |
|||
} |
|||
Y = Z; // This is not part of the if statement. It will execute even if K doesn't equal 3. |
|||
}</syntaxhighlight> |
|||
{Id Head} = {Letter} + [_] |
|||
{Id Tail} = {Id Head} + {Digit} |
|||
===Semicolons=== |
|||
{String Ch} = {Printable} - ["] |
|||
Any "executable" statement must end in a semicolon, such as an assignment or function call. If you get an error message from your compiler, it won't explicitly tell you "Expected semicolon at end of line X." Go to the line number it says the error is at, and look a few lines <i>above</i> that. You might have forgotten a semicolon there. |
|||
{Char Ch} = {Printable} - [''] |
|||
===Scope=== |
|||
DecLiteral = [123456789]{digit}* |
|||
Unlike assembly which lets you jump anywhere or read any memory address, C imposes restrictions on labeled values. A variable defined inside a function can only be "seen" by that function, and not the ones outside it. Furthermore, you can re-use variable names inside a function and it refers to a different entity than the variable of the same name defined outside. |
|||
OctLiteral = 0{Oct Digit}* |
|||
HexLiteral = 0x{Hex Digit}+ |
|||
FloatLiteral = {Digit}*'.'{Digit}+ |
|||
===Functions=== |
|||
StringLiteral = '"'( {String Ch} | '\'{Printable} )* '"' |
|||
A function is made up of three parts: its return type, its name, and its arguments. |
|||
CharLiteral = '' ( {Char Ch} | '\'{Printable} )'' |
|||
<syntaxhighlight lang="c">int main(void) // This is the function "main," which takes no arguments and returns a 32-bit signed integer value. |
|||
int sum(int a, int b) // This is the function "sum," which takes two integer arguments and returns an integer. |
|||
Id = {Id Head}{Id Tail}* |
|||
void PlaySound(char songName) |
|||
// This takes a character string as an argument and presumably sends a command to sound hardware. |
|||
// It returns no values. Functions that have a return value of "void" typically do some sort of |
|||
// procedure whose outcome does not need to be measured or remembered later.</syntaxhighlight> |
|||
Note that the variable names listed as arguments when declaring a function are known as <i>formal parameters</i> and only are there to define the function. Variables with those names need not be declared or defined in your actual function, nor do they refer to any variables in your program that happen to have the same name. Essentially, formal parameters act as placeholders for the actual function parameters that you'll be using. |
|||
! =================================================================== |
|||
<syntaxhighlight lang="c">int foo(int x) { |
|||
! Comments |
|||
return x; |
|||
! =================================================================== |
|||
} // "x" doesn't need to be a variable in your real program. If it is, that's not related in any way to the "x" here. |
|||
int main() { |
|||
Comment Start = '/*' |
|||
Comment End = '*/' |
|||
Comment Line = '//' |
|||
int y; |
|||
int z = 2; |
|||
y = foo(z); // Note that x was never involved. That's because the "x" earlier was the formal parameter. |
|||
! Typically, C comments cannot be nested. As a result, the |
|||
! Comment Start and Comment End terminals cannot be used. |
|||
! |
|||
! To implement non-nested comments, the whitespace terminal is |
|||
! modified to accept them. In the definition below, Whitespace |
|||
! is defined as one or more {Whitespace} characters OR a series |
|||
! of characters delimited by /* and */. Note that the characters |
|||
! between the two delimiters cannot contain the */ sequence. |
|||
! |
|||
! Uncomment the following to prevent block commments. Make sure |
|||
! to comment the Comment Start and Comment End definitions. |
|||
! |
|||
! {Non Slash} = {Printable} - [/] |
|||
! {Non Asterisk} = {Printable} - [*] |
|||
! |
|||
! Whitespace = {Whitespace}+ |
|||
! | '/*' ( {Non Asterisk} | '*' {Non Slash}? )* '*/' |
|||
}</syntaxhighlight> |
|||
!======================================================= |
|||
===Assignment=== |
|||
<Decls> ::= <Decl> <Decls> |
|||
C allows you to define a variable as equal to a value, in more ways than just simple numerals. |
|||
| |
|||
<syntaxhighlight lang="c">int a = 3; // Declare the variable a of type int, define it equal to decimal 3. |
|||
int b = -1; // Declare the variable b of type int and equal to -1 (0xFFFFFFFF in hex). |
|||
<Decl> ::= <Func Decl> |
|||
| <Func Proto> |
|||
| <Struct Decl> |
|||
| <Union Decl> |
|||
| <Enum Decl> |
|||
| <Var Decl> |
|||
| <Typedef Decl> |
|||
! =================================================================== |
|||
! Function Declaration |
|||
! =================================================================== |
|||
char letter = "A"; |
|||
<Func Proto> ::= <Func ID> '(' <Types> ')' ';' |
|||
// Declare the variable "letter" of type char and equal to capital A. |
|||
| <Func ID> '(' <Params> ')' ';' |
|||
// C allows you to treat an ascii value as its numeric equivalent whenever you feel like it. Other languages do not. |
|||
| <Func ID> '(' ')' ';' |
|||
char *myString = "Hello"; // Define the array "myString" containing the letters "Hello" followed by a null terminator. |
|||
<Func Decl> ::= <Func ID> '(' <Params> ')' <Block> |
|||
| <Func ID> '(' <Id List> ')' <Struct Def> <Block> |
|||
| <Func ID> '(' ')' <Block> |
|||
int myArray[5] = {10, 20, 30, 40, 50}; |
|||
// Declare the array variable "myArray" containing integer values, with a maximum size of 5 elements. |
|||
// Then assign 10 to the beginning, 20 after it, 30 after that, and so on. |
|||
int c = sum(a, b); |
|||
<Params> ::= <Param> ',' <Params> |
|||
// Declare the integer variable "c". |
|||
| <Param> |
|||
// Define it to equal the output of the function sum using the previously defined variables "a" and "b" as arguments. |
|||
// When this line of code is executed, the computer will perform the function "sum(a,b)" and store the result in c. |
|||
<Param> ::= const <Type> ID |
|||
// This is only valid if the return type of the function "sum" matches the type of the variable "c."</syntaxhighlight> |
|||
| <Type> ID |
|||
<Types> ::= <Type> ',' <Types> |
|||
| <Type> |
|||
<Id List> ::= Id ',' <Id List> |
|||
| Id |
|||
===Declaring vs. Defining=== |
|||
<Func ID> ::= <Type> ID |
|||
This is a very unintuitive aspect of C that often confuses new users. Declaring a variable or function tells the compiler that a function may exist. Defining a variable or function assigns it a value or procedure, respectively. Compare the two examples below: |
|||
| ID |
|||
<syntaxhighlight lang="c">int a; // The variable "a" has been declared, but not defined. |
|||
a = 2; // Now the variable has been defined.</syntaxhighlight> |
|||
<syntaxhighlight lang="c">int a = 2; // The variable "a" has been both declared and defined.</syntaxhighlight> |
|||
! =================================================================== |
|||
! Type Declaration |
|||
! =================================================================== |
|||
* You cannot define a variable without declaring it first. |
|||
<Typedef Decl> ::= typedef <Type> ID ';' |
|||
* Before a variable can be used, it must be defined. |
|||
===Types=== |
|||
<Struct Decl> ::= struct Id '{' <Struct Def> '}' ';' |
|||
C has the following types built in by default, but you can create your own based on these using the <code>typedef</code> directive. This is not an exhaustive list. Some of these names will have different meanings depending on the hardware you're programming for. |
|||
* <code>char</code>: an 8 bit value, typically used to represent ASCII characters. |
|||
* <code>short</code>: a 16 bit value. |
|||
* <code>int</code>: a 32 bit value. |
|||
* <code>struct</code>: a collection of several other values, stored consecutively in memory. Each can be a different type. |
|||
* <code>union</code>: a variable that can hold several different types of data, but only one at a time. |
|||
* <code>float</code>: a single-precision (32-bit) floating-point decimal value. |
|||
You can also add a few modifiers in front of the variable type to be more specific: |
|||
<Union Decl> ::= union Id '{' <Struct Def> '}' ';' |
|||
* <code>unsigned</code> tells the compiler that this variable is always treated as positive. Computers use two's complement to represent negative numbers, meaning that if the leftmost bit of a number's binary equivalent is set, the value is considered negative. The resulting assembly code will use unsigned comparisons to check this variable against other variables. |
|||
* <code>volatile</code> tells the compiler that this variable's value can changed by the hardware. This is commonly used for hardware registers such as those that track the mouse cursor's location, a scanline counter, etc. The value will always be read from its original memory location, ensuring that its value is always up-to-date. |
|||
Examples: |
|||
<syntaxhighlight lang="c">unsigned int x; |
|||
volatile int HorizontalScroll;</syntaxhighlight> |
|||
Functions are declared in a similar fashion to variables, except a function's "type" is the type of the value it returns. |
|||
<Struct Def> ::= <Var Decl> <Struct Def> |
|||
<syntaxhighlight lang="c">int foo(int bar); |
|||
| <Var Decl> |
|||
// The function foo was declared. It takes an integer as an argument and returns an integer. |
|||
// What it actually does is currently unknown but can be defined later.</syntaxhighlight> |
|||
==Citation== |
|||
! =================================================================== |
|||
*[[wp:C_%28programming_language%29|Wikipedia:C (programming language)]] |
|||
! Variable Declaration |
|||
! =================================================================== |
|||
==Todo== |
|||
<Var Decl> ::= <Mod> <Type> <Var> <Var List> ';' |
|||
* [[Tasks not implemented in C]] |
|||
| <Type> <Var> <Var List> ';' |
|||
| <Mod> <Var> <Var List> ';' |
|||
<Var> ::= ID <Array> |
|||
| ID <Array> '=' <Op If> |
|||
<Array> ::= '[' <Expr> ']' |
|||
| '[' ']' |
|||
| |
|||
<Var List> ::= ',' <Var Item> <Var List> |
|||
| |
|||
{{language programming paradigm|Imperative}} |
|||
<Var Item> ::= <Pointers> <Var> |
|||
<Mod> ::= extern |
|||
| static |
|||
| register |
|||
| auto |
|||
| volatile |
|||
| const |
|||
! =================================================================== |
|||
! Enumerations |
|||
! =================================================================== |
|||
<Enum Decl> ::= enum Id '{' <Enum Def> '}' ';' |
|||
<Enum Def> ::= <Enum Val> ',' <Enum Def> |
|||
| <Enum Val> |
|||
<Enum Val> ::= Id |
|||
| Id '=' OctLiteral |
|||
| Id '=' HexLiteral |
|||
| Id '=' DecLiteral |
|||
! =================================================================== |
|||
! Types |
|||
! =================================================================== |
|||
<Type> ::= <Base> <Pointers> |
|||
<Base> ::= <Sign> <Scalar> |
|||
| struct Id |
|||
| struct '{' <Struct Def> '}' |
|||
| union Id |
|||
| union '{' <Struct Def> '}' |
|||
| enum Id |
|||
<Sign> ::= signed |
|||
| unsigned |
|||
| |
|||
<Scalar> ::= char |
|||
| int |
|||
| short |
|||
| long |
|||
| short int |
|||
| long int |
|||
| float |
|||
| double |
|||
| void |
|||
<Pointers> ::= '*' <Pointers> |
|||
| |
|||
! =================================================================== |
|||
! Statements |
|||
! =================================================================== |
|||
<Stm> ::= <Var Decl> |
|||
| Id ':' !Label |
|||
| if '(' <Expr> ')' <Stm> |
|||
| if '(' <Expr> ')' <Then Stm> else <Stm> |
|||
| while '(' <Expr> ')' <Stm> |
|||
| for '(' <Arg> ';' <Arg> ';' <Arg> ')' <Stm> |
|||
| <Normal Stm> |
|||
<Then Stm> ::= if '(' <Expr> ')' <Then Stm> else <Then Stm> |
|||
| while '(' <Expr> ')' <Then Stm> |
|||
| for '(' <Arg> ';' <Arg> ';' <Arg> ')' <Then Stm> |
|||
| <Normal Stm> |
|||
<Normal Stm> ::= do <Stm> while '(' <Expr> ')' |
|||
| switch '(' <Expr> ')' '{' <Case Stms> '}' |
|||
| <Block> |
|||
| <Expr> ';' |
|||
| goto Id ';' |
|||
| break ';' |
|||
| continue ';' |
|||
| return <Expr> ';' |
|||
| ';' !Null statement |
|||
<Arg> ::= <Expr> |
|||
| |
|||
<Case Stms> ::= case <Value> ':' <Stm List> <Case Stms> |
|||
| default ':' <Stm List> |
|||
| |
|||
<Block> ::= '{' <Stm List> '}' |
|||
<Stm List> ::= <Stm> <Stm List> |
|||
| |
|||
! =================================================================== |
|||
! Here begins the C's 15 levels of operator precedence. |
|||
! =================================================================== |
|||
<Expr> ::= <Expr> ',' <Op Assign> |
|||
| <Op Assign> |
|||
<Op Assign> ::= <Op If> '=' <Op Assign> |
|||
| <Op If> '+=' <Op Assign> |
|||
| <Op If> '-=' <Op Assign> |
|||
| <Op If> '*=' <Op Assign> |
|||
| <Op If> '/=' <Op Assign> |
|||
| <Op If> '^=' <Op Assign> |
|||
| <Op If> '&=' <Op Assign> |
|||
| <Op If> '|=' <Op Assign> |
|||
| <Op If> '>>=' <Op Assign> |
|||
| <Op If> '<<=' <Op Assign> |
|||
| <Op If> |
|||
<Op If> ::= <Op Or> '?' <Op If> ':' <Op If> |
|||
| <Op Or> |
|||
<Op Or> ::= <Op Or> '||' <Op And> |
|||
| <Op And> |
|||
<Op And> ::= <Op And> '&&' <Op BinOR> |
|||
| <Op BinOR> |
|||
<Op BinOR> ::= <Op BinOr> '|' <Op BinXOR> |
|||
| <Op BinXOR> |
|||
<Op BinXOR> ::= <Op BinXOR> '^' <Op BinAND> |
|||
| <Op BinAND> |
|||
<Op BinAND> ::= <Op BinAND> '&' <Op Equate> |
|||
| <Op Equate> |
|||
<Op Equate> ::= <Op Equate> '==' <Op Compare> |
|||
| <Op Equate> '!=' <Op Compare> |
|||
| <Op Compare> |
|||
<Op Compare> ::= <Op Compare> '<' <Op Shift> |
|||
| <Op Compare> '>' <Op Shift> |
|||
| <Op Compare> '<=' <Op Shift> |
|||
| <Op Compare> '>=' <Op Shift> |
|||
| <Op Shift> |
|||
<Op Shift> ::= <Op Shift> '<<' <Op Add> |
|||
| <Op Shift> '>>' <Op Add> |
|||
| <Op Add> |
|||
<Op Add> ::= <Op Add> '+' <Op Mult> |
|||
| <Op Add> '-' <Op Mult> |
|||
| <Op Mult> |
|||
<Op Mult> ::= <Op Mult> '*' <Op Unary> |
|||
| <Op Mult> '/' <Op Unary> |
|||
| <Op Mult> '%' <Op Unary> |
|||
| <Op Unary> |
|||
<Op Unary> ::= '!' <Op Unary> |
|||
| '~' <Op Unary> |
|||
| '-' <Op Unary> |
|||
| '*' <Op Unary> |
|||
| '&' <Op Unary> |
|||
| '++' <Op Unary> |
|||
| '--' <Op Unary> |
|||
| <Op Pointer> '++' |
|||
| <Op Pointer> '--' |
|||
| '(' <Type> ')' <Op Unary> !CAST |
|||
| sizeof '(' <Type> ')' |
|||
| sizeof '(' ID <Pointers> ')' |
|||
| <Op Pointer> |
|||
<Op Pointer> ::= <Op Pointer> '.' <Value> |
|||
| <Op Pointer> '->' <Value> |
|||
| <Op Pointer> '[' <Expr> ']' |
|||
| <Value> |
|||
<Value> ::= OctLiteral |
|||
| HexLiteral |
|||
| DecLiteral |
|||
| StringLiteral |
|||
| CharLiteral |
|||
| FloatLiteral |
|||
| Id '(' <Expr> ')' |
|||
| Id '(' ')' |
|||
| Id |
|||
| '(' <Expr> ')' |
|||
</pre> |
Latest revision as of 10:21, 1 August 2023
This programming language may be used to instruct a computer to perform a task.
Execution method: | Compiled (machine code) |
---|---|
Garbage collected: | No |
Parameter passing methods: | By value |
Type safety: | Unsafe |
Type strength: | Weak |
Type compatibility: | Nominative |
Type expression: | Explicit |
Type checking: | Static |
Lang tag(s): | c |
See Also: |
C is a general-purpose, procedural, imperative computer programming language developed in 1972 by Dennis Ritchie at the Bell Telephone Laboratories for use with the UNIX operating system. C evolved from its predecessor, B.
C has since spread to many other platforms, and is now one of the most widely used programming languages. C has also greatly influenced many other popular languages, such as C++ and Objective-C, which were originally designed as enhancements to C. People are so familiar with its syntax that many other languages such as AWK, PHP, Java, JavaScript, D, and C# deliberately used its "look and feel". C is the most commonly used programming language for writing system software, though it is also widely used for writing applications. C is the lingua franca of the open source community.
Versions
- K&R C was the first widely-used form of C. It was originally documented in The C Programming Language, published in 1978. It is named for the authors, Brian Kernighan and Dennis Ritchie (also the language's creator). Code in this style is virtually nonexistent today.
- C89 (often called ANSI C) is the version of C standardized by ANSI in 1989. It is the most commonly used and supported version of the language.
- C90 (often called ISO C) is identical to C89, republished by ISO in 1990.
- C99 is a significant improvement, adopting many features of C++ and standardizing common compiler extensions. It was standardized by ISO in 1999, and by ANSI in 2000. It is primarily supported by commercial C compilers, but most of its features are available in Clang GCC. [1]
- C11 is the previous standard, published in December 2011. It is the default for GCC as of version 5.1.
- C18 is the current standard, published in June 2018. It is the default for GCC as of version 8.1.
- C2x is the upcoming standard, expected to be voted on in 2023 - it will then become C23. GCC 9, Clang 9 and Pelles C 11 have preliminary support for it.
Overview
Curly Braces
C uses curly braces as a separator for sections of code. All curly braces must be "balanced," i.e. every left curly brace must have a right curly brace after it. Nesting curly brace pairs inside curly braces is also acceptable as long as none of them are "lonely."
Most advanced code editors will help you with curly braces by automatically typing the right brace as soon as you type the left one. It is a matter of style as to whether you prefer to place an opening curly brace on its own line or at the end of the previous line. Here we use the latter style.
int main() {
// Your main program goes here.
// If you forgot either of these curly braces you would get an error message when you try to compile!
}
The contents of a function, if statement, etc. must be enclosed in curly braces for the code to count as part of that section.
{
// This wouldn't actually compile as none of these variables were declared in this scope. More on that later.
if (K == 3) {
X = Y; // This line will be skipped if K doesn't equal 3.
}
Y = Z; // This is not part of the if statement. It will execute even if K doesn't equal 3.
}
Semicolons
Any "executable" statement must end in a semicolon, such as an assignment or function call. If you get an error message from your compiler, it won't explicitly tell you "Expected semicolon at end of line X." Go to the line number it says the error is at, and look a few lines above that. You might have forgotten a semicolon there.
Scope
Unlike assembly which lets you jump anywhere or read any memory address, C imposes restrictions on labeled values. A variable defined inside a function can only be "seen" by that function, and not the ones outside it. Furthermore, you can re-use variable names inside a function and it refers to a different entity than the variable of the same name defined outside.
Functions
A function is made up of three parts: its return type, its name, and its arguments.
int main(void) // This is the function "main," which takes no arguments and returns a 32-bit signed integer value.
int sum(int a, int b) // This is the function "sum," which takes two integer arguments and returns an integer.
void PlaySound(char songName)
// This takes a character string as an argument and presumably sends a command to sound hardware.
// It returns no values. Functions that have a return value of "void" typically do some sort of
// procedure whose outcome does not need to be measured or remembered later.
Note that the variable names listed as arguments when declaring a function are known as formal parameters and only are there to define the function. Variables with those names need not be declared or defined in your actual function, nor do they refer to any variables in your program that happen to have the same name. Essentially, formal parameters act as placeholders for the actual function parameters that you'll be using.
int foo(int x) {
return x;
} // "x" doesn't need to be a variable in your real program. If it is, that's not related in any way to the "x" here.
int main() {
int y;
int z = 2;
y = foo(z); // Note that x was never involved. That's because the "x" earlier was the formal parameter.
}
Assignment
C allows you to define a variable as equal to a value, in more ways than just simple numerals.
int a = 3; // Declare the variable a of type int, define it equal to decimal 3.
int b = -1; // Declare the variable b of type int and equal to -1 (0xFFFFFFFF in hex).
char letter = "A";
// Declare the variable "letter" of type char and equal to capital A.
// C allows you to treat an ascii value as its numeric equivalent whenever you feel like it. Other languages do not.
char *myString = "Hello"; // Define the array "myString" containing the letters "Hello" followed by a null terminator.
int myArray[5] = {10, 20, 30, 40, 50};
// Declare the array variable "myArray" containing integer values, with a maximum size of 5 elements.
// Then assign 10 to the beginning, 20 after it, 30 after that, and so on.
int c = sum(a, b);
// Declare the integer variable "c".
// Define it to equal the output of the function sum using the previously defined variables "a" and "b" as arguments.
// When this line of code is executed, the computer will perform the function "sum(a,b)" and store the result in c.
// This is only valid if the return type of the function "sum" matches the type of the variable "c."
Declaring vs. Defining
This is a very unintuitive aspect of C that often confuses new users. Declaring a variable or function tells the compiler that a function may exist. Defining a variable or function assigns it a value or procedure, respectively. Compare the two examples below:
int a; // The variable "a" has been declared, but not defined.
a = 2; // Now the variable has been defined.
int a = 2; // The variable "a" has been both declared and defined.
- You cannot define a variable without declaring it first.
- Before a variable can be used, it must be defined.
Types
C has the following types built in by default, but you can create your own based on these using the typedef
directive. This is not an exhaustive list. Some of these names will have different meanings depending on the hardware you're programming for.
char
: an 8 bit value, typically used to represent ASCII characters.short
: a 16 bit value.int
: a 32 bit value.struct
: a collection of several other values, stored consecutively in memory. Each can be a different type.union
: a variable that can hold several different types of data, but only one at a time.float
: a single-precision (32-bit) floating-point decimal value.
You can also add a few modifiers in front of the variable type to be more specific:
unsigned
tells the compiler that this variable is always treated as positive. Computers use two's complement to represent negative numbers, meaning that if the leftmost bit of a number's binary equivalent is set, the value is considered negative. The resulting assembly code will use unsigned comparisons to check this variable against other variables.volatile
tells the compiler that this variable's value can changed by the hardware. This is commonly used for hardware registers such as those that track the mouse cursor's location, a scanline counter, etc. The value will always be read from its original memory location, ensuring that its value is always up-to-date.
Examples:
unsigned int x;
volatile int HorizontalScroll;
Functions are declared in a similar fashion to variables, except a function's "type" is the type of the value it returns.
int foo(int bar);
// The function foo was declared. It takes an integer as an argument and returns an integer.
// What it actually does is currently unknown but can be defined later.
Citation
Todo
Subcategories
This category has the following 3 subcategories, out of 3 total.
@
- C examples needing attention (5 P)
- C Implementations (5 P)
- C User (468 P)
Pages in category "C"
The following 200 pages are in this category, out of 1,297 total.
(previous page) (next page)C
- Compare a list of strings
- Compare length of two strings
- Compare sorting algorithms' performance
- Compile-time calculation
- Compiler/AST interpreter
- Compiler/code generator
- Compiler/lexical analyzer
- Compiler/syntax analyzer
- Compiler/Verifying syntax
- Compiler/virtual machine interpreter
- Composite numbers k with no single digit factors whose factors are all substrings of k
- Compound data type
- Concatenate two primes is also prime
- Concurrent computing
- Conditional structures
- Conjugate transpose
- Consecutive primes with ascending or descending differences
- Consistent overhead byte stuffing
- Constrained random points on a circle
- Continued fraction
- Continued fraction/Arithmetic/Construct from rational number
- Continued fraction/Arithmetic/G(matrix ng, continued fraction n)
- Continued fraction/Arithmetic/G(matrix ng, continued fraction n1, continued fraction n2)
- Convert decimal number to rational
- Convert seconds to compound duration
- Convex hull
- Conway's Game of Life
- Coprime triplets
- Coprimes
- Copy a string
- Copy stdin to stdout
- CORDIC
- Count how many vowels and consonants occur in a string
- Count in factors
- Count in octal
- Count occurrences of a substring
- Count the coins
- Cousin primes
- Cramer's rule
- CRC-32
- Create a file
- Create a file on magnetic tape
- Create a two-dimensional array at runtime
- Create an HTML table
- Create an object at a given address
- CSV data manipulation
- CSV to HTML translation
- Cuban primes
- Cubic special primes
- Cumulative standard deviation
- Currency
- Currying
- Curzon numbers
- CUSIP
- Cut a rectangle
- Cycle detection
D
- Damm algorithm
- Data Encryption Standard
- Date format
- Date manipulation
- Day of the week
- Day of the week of Christmas and New Year
- Days between dates
- De Polignac numbers
- Deal cards for FreeCell
- Death Star
- Deceptive numbers
- Decision tables
- Deconvolution/1D
- Deconvolution/2D+
- Decorate-sort-undecorate idiom
- Deepcopy
- Delegates
- Delete a file
- Department numbers
- Descending primes
- Detect division by zero
- Determinant and permanent
- Determine if a string has all the same characters
- Determine if a string has all unique characters
- Determine if a string is collapsible
- Determine if a string is numeric
- Determine if a string is squeezable
- Determine if only one instance is running
- Determine if two triangles overlap
- Dice game probabilities
- Digit fifth powers
- Digital root
- Digital root/Multiplicative digital root
- Dijkstra's algorithm
- Dinesman's multiple-dwelling problem
- Dining philosophers
- Diophantine linear system solving
- Disarium numbers
- Discordian date
- Display a linear combination
- Distinct power numbers
- Distributed programming
- Diversity prediction theorem
- DNS query
- Documentation
- Doomsday rule
- Dot product
- Double Twin Primes
- Doubly-linked list/Definition
- Doubly-linked list/Element definition
- Doubly-linked list/Element insertion
- Doubly-linked list/Traversal
- Dragon curve
- Draw a clock
- Draw a cuboid
- Draw a pixel
- Draw a rotating cube
- Draw a sphere
- Draw pixel 2
- Dutch national flag problem
E
- Eban numbers
- Echo server
- Egyptian division
- EKG sequence convergence
- Element-wise operations
- Elementary cellular automaton
- Elementary cellular automaton/Random number generator
- Elliptic curve arithmetic
- Elliptic Curve Digital Signature Algorithm
- Emirp primes
- Empty directory
- Empty program
- Empty string
- Enforced immutability
- Entropy
- Entropy/Narcissist
- Enumerations
- Environment variables
- Equilibrium index
- Erdős-Nicolas numbers
- Erdős-primes
- Esthetic numbers
- Ethiopian multiplication
- Euler method
- Euler's constant 0.5772...
- Euler's identity
- Euler's sum of powers conjecture
- Evaluate binomial coefficients
- Even or odd
- Events
- Evolutionary algorithm
- Exactly three adjacent 3 in lists
- Exceptions
- Exceptions/Catch an exception thrown in a nested call
- Executable library
- Execute a Markov algorithm
- Execute a system command
- Execute Brain****
- Execute HQ9+
- Execute SNUSP
- Exponentiation operator
- Exponentiation order
- Extend your language
- Extensible prime generator
- Extra primes
- Extract file extension
- Extreme floating point values
- Extreme primes
F
- Factorial
- Factorions
- Factors of a Mersenne number
- Factors of an integer
- Fairshare between two and more
- Farey sequence
- Fast Fourier transform
- FASTA format
- Faulhaber's formula
- Faulhaber's triangle
- Feigenbaum constant calculation
- Fermat numbers
- Fibonacci n-step number sequences
- Fibonacci sequence
- Fibonacci word
- Fibonacci word/fractal
- File extension is in extensions list
- File input/output
- File modification time
- File size
- File size distribution
- Filter
- Find adjacent primes which differ by a square integer
- Find common directory path
- Find first and last set bit of a long integer
- Find if a point is within a triangle
- Find largest left truncatable prime in a given base
- Find limit of recursion
- Find minimum number of coins that make a given value
- Find palindromic numbers in both binary and ternary bases
- Find prime n such that reversed n is also prime
- Find prime numbers of the form n*n*n+2
- Find square difference
- Find squares n where n+1 is prime
- Find the intersection of a line with a plane
- Find the intersection of two lines