Category:C
![Language](http://static.miraheze.org/rosettacodewiki/thumb/2/27/Rcode-button-language-crushed.png/64px-Rcode-button-language-crushed.png)
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.
<lang C>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!
}</lang>
The contents of a function, if statement, etc. must be enclosed in curly braces for the code to count as part of that section. <lang C>int main() {
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.
}</lang>
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. <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.
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.</lang>
Note that the variable names listed as arguments when declaring a function are just for convenience. They need not be declared nor defined, nor do they refer to any variables in your program that happen to have the same name. It's only when a function is actually used are the argument variables required to exist. <lang C>int foo(int x){ return x; } // the "x" here is just a placeholder for whatever actually goes in when you invoke foo.
int main() {
int y; int z = 2;
y = foo(z); //note that x was never involved. That's because the "x" earlier was just a placeholder name.
}</lang>
Assignment
C allows you to define a variable as equal to a value, in more ways than just simple numerals. <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, define it equal to -1 (0xFFFFFFFF in hex)
char letter = "A"; //declare the variable "letter" of type char, it equals 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."</lang>
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: <lang C>int a; // The variable "a" has been declared, but not defined. a = 2; // Now the variable has been defined.</lang>
<lang C>int a = 2; //The variable "a" has been both declared and defined.</lang>
- 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: <lang C>unsigned int x; volatile int HorizontalScroll;</lang>
Functions are declared in a similar fashion to variables, except a function's "type" is the type of the value it returns. <lang C>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.</lang>
Citation
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,298 total.
(previous page) (next page)S
- Sieve of Eratosthenes
- Simple database
- Simple windowed application
- Simulate input/Keyboard
- Simulate input/Mouse
- Simulated annealing
- Sine wave
- Singleton
- Singly-linked list/Element definition
- Singly-linked list/Element insertion
- Singly-linked list/Element removal
- Singly-linked list/Reversal
- Singly-linked list/Traversal
- Singular value decomposition
- Sleep
- Smallest power of 6 whose decimal expansion contains n
- Smallest square that begins with n
- Smarandache prime-digital sequence
- Smarandache-Wellin primes
- Smith numbers
- Snake
- Snake and ladder
- SOAP
- Sockets
- Sokoban
- Soloway's recurring rainfall
- Solve a Hidato puzzle
- Solve the no connection puzzle
- Sort a list of object identifiers
- Sort an array of composite structures
- Sort an integer array
- Sort disjoint sublist
- Sort numbers lexicographically
- Sort stability
- Sort the letters of string in alphabetical order
- Sort three variables
- Sort using a custom comparator
- Sorting algorithms/Bead sort
- Sorting algorithms/Bogosort
- Sorting algorithms/Bubble sort
- Sorting Algorithms/Circle Sort
- Sorting algorithms/Cocktail sort
- Sorting algorithms/Cocktail sort with shifting bounds
- Sorting algorithms/Comb sort
- Sorting algorithms/Counting sort
- Sorting algorithms/Cycle sort
- Sorting algorithms/Gnome sort
- Sorting algorithms/Heapsort
- Sorting algorithms/Insertion sort
- Sorting algorithms/Merge sort
- Sorting algorithms/Pancake sort
- Sorting algorithms/Patience sort
- Sorting algorithms/Permutation sort
- Sorting algorithms/Quicksort
- Sorting algorithms/Radix sort
- Sorting algorithms/Selection sort
- Sorting algorithms/Shell sort
- Sorting algorithms/Sleep sort
- Sorting algorithms/Stooge sort
- Sorting algorithms/Strand sort
- Sorting algorithms/Tree sort on a linked list
- Soundex
- Sparkline in unicode
- Special characters
- Special divisors
- Special factorials
- Special neighbor primes
- Special variables
- Speech synthesis
- Spelling of ordinal numbers
- Sphenic numbers
- Spinning rod animation/Text
- Spiral matrix
- Split a character string based on change of character
- Spoof game
- SQL-based authentication
- Square but not cube
- Square form factorization
- Square-free integers
- Stable marriage problem
- Stack
- Stack traces
- Stair-climbing puzzle
- Start from a main routine
- State name puzzle
- Statistics/Basic
- Statistics/Normal distribution
- Steady squares
- Steffensen's method
- Stem-and-leaf plot
- Stern-Brocot sequence
- Stirling numbers of the first kind
- Stirling numbers of the second kind
- Straddling checkerboard
- Strange numbers
- Strange plus numbers
- Strange unique prime triplets
- Stream merge
- String append
- String case
- String comparison
- String concatenation
- String interpolation (included)
- String length
- String matching
- String prepend
- Strip a set of characters from a string
- Strip block comments
- Strip comments from a string
- Strip control codes and extended characters from a string
- Strip whitespace from a string/Top and tail
- Strong and weak primes
- Subleq
- Subset sum problem
- Substitution cipher
- Substring
- Substring/Top and tail
- Subtractive generator
- Successive prime differences
- Sudan function
- Sudoku
- Sum and product of an array
- Sum and product puzzle
- Sum data type
- Sum digits of an integer
- Sum multiples of 3 and 5
- Sum of a series
- Sum of divisors
- Sum of elements below main diagonal of matrix
- Sum of first n cubes
- Sum of primes in odd positions is prime
- Sum of square and cube digits of an integer are primes
- Sum of squares
- Sum of the digits of n is substring of n
- Sum of two adjacent numbers are primes
- Sum to 100
- Summarize and say sequence
- Summarize primes
- Summation of primes
- Sunflower fractal
- Super-d numbers
- Superellipse
- Superpermutation minimisation
- Sutherland-Hodgman polygon clipping
- Symmetric difference
- Synchronous concurrency
- System time
T
- Table creation
- Table creation/Postal addresses
- Take notes on the command line
- Tarjan
- Tau function
- Tau number
- Taxicab numbers
- Teacup rim text
- Temperature conversion
- Terminal control/Clear the screen
- Terminal control/Coloured text
- Terminal control/Cursor movement
- Terminal control/Cursor positioning
- Terminal control/Dimensions
- Terminal control/Display an extended character
- Terminal control/Hiding the cursor
- Terminal control/Inverse video
- Terminal control/Positional read
- Terminal control/Preserve screen
- Terminal control/Ringing the terminal bell
- Terminal control/Unicode output
- Ternary logic
- Test a function
- Test integerness
- Tetris
- Text between
- Text processing/1
- Text processing/2
- Text processing/Max licenses in use
- Textonyms
- The ISAAC cipher
- The Name Game
- The sieve of Sundaram
- The Twelve Days of Christmas
- Thiele's interpolation formula
- Three word location
- Thue-Morse
- Tic-tac-toe
- Time a function
- Tokenize a string
- Tokenize a string with escaping
- Tonelli-Shanks algorithm
- Top rank per group
- Topological sort
- Topological sort/Extracted top item
- Topswops
- Total circles area
- Totient function
- Towers of Hanoi
- Trabb Pardo–Knuth algorithm
- Tree traversal
- Trigonometric functions
- Triplet of three numbers