[go: nahoru, domu]

Jump to content

Programming idiom

From Wikipedia, the free encyclopedia

This is an old revision of this page, as edited by Joe n bloe (talk | contribs) at 16:25, 31 August 2006 (→‎Examples: proper subheading markup). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.

A programming idiom is a means of expressing a recurring construct in one or more programming languages. Generally speaking, a programming idiom is an expression of a simple task or algorithm that is not a built-in feature in the programming language being used, or, conversely, the use of an unusual or notable feature that is built in to a programming language. The term can be used more broadly, however, to refer to complex algorithms or programming design patterns.

Knowing the idioms associated with a programming language and how to use them is an important part of gaining fluency in that language.

Examples

Incrementing a counter

In a language like Pascal, the code to increment a counter by one is mundane:

 i := i + 1;

The C programming language and many others derived from it have language-specific features that make this code shorter:

 i += 1; /* i = i + 1; */
 i++;    /* same       */

This is the idiomatic way of "adding one to a counter" in C and similar languages.

Swapping values between variables

In many languages, code for swapping the values in two variables looks like the following:

 temp = a;
 a = b;
 b = temp;

In Perl, the list assignment syntax allows a more succinct expression:

 ($a, $b) = ($b, $a);

Infinite loop

The code used to write an infinite (nonterminating) loop varies widely between different programming languages, although it often takes the form of a while loop where the test condition is always true. In Pascal, for example:

 while true do begin
   do_something();
 end;

There are several ways to write an infinite loop in C, including a loop very similar to the Pascal example, but the following idiom uses the unusual appearance of the empty for loop condition to draw attention visually to the loop:

 for (;;) {
   do_something();
 }

Perl allows the C syntax above, but supports some other syntax as well. For example:

 do_something() while (1);  # Succinct one-line infinite loop
 
 # Using a "naked block" and the redo operator
 {
   do_something();
   redo;
 }