Imperative programming: Difference between revisions

From Wikipedia, the free encyclopedia
Jump to navigation Jump to search
imported>Jerryobject
 
(One intermediate revision by one other user not shown)
Line 1: Line 1:
{{Short description|Type of programming paradigm in computer science}}
{{Short description|Type of programming paradigm in computer science}}
{{more citations needed|date=October 2011}}
{{more citations needed|date=October 2011}}
In [[computer science]], '''imperative programming''' is a [[programming paradigm]] of [[software]] that uses [[Statement (computer science)|statement]]s that change a program's [[state (computer science)|state]]. In much the same way that the [[imperative mood]] in [[natural language]]s expresses commands, an imperative program consists of [[command (computing)|command]]s for the [[computer]] to perform. Imperative programming focuses on describing ''how'' a program operates step by step (with general order of the steps being determined in [[source code]] by the placement of statements one below the other),<ref>{{Cite web |last=Jain |first=Anisha |date=2022-12-10 |title=Javascript Promises— Is There a Better Approach? |url=https://medium.datadriveninvestor.com/javascript-promises-is-there-a-better-approach-dd6a0a329131 |access-date=2022-12-20 |website=Medium |language=en |archive-date=2022-12-20 |archive-url=https://web.archive.org/web/20221220020247/https://medium.datadriveninvestor.com/javascript-promises-is-there-a-better-approach-dd6a0a329131 |url-status=live }}</ref> rather than on high-level descriptions of its expected results.
In [[computer science]], '''imperative programming''' is a [[programming paradigm]] of [[software]] that uses [[Statement (computer science)|statement]]s that change a process' [[state (computer science)|state]]. In much the same way that the [[imperative mood]] in [[natural language]]s expresses commands, an imperative program consists of [[command (computing)|command]]s for the [[computer]] to perform. Imperative programming focuses on describing ''how'' a program operates step by step (with general order of the steps being determined in [[source code]] by the placement of statements one below the other),<ref>{{Cite web |last=Jain |first=Anisha |date=2022-12-10 |title=Javascript Promises— Is There a Better Approach? |url=https://medium.datadriveninvestor.com/javascript-promises-is-there-a-better-approach-dd6a0a329131 |access-date=2022-12-20 |website=Medium |language=en |archive-date=2022-12-20 |archive-url=https://web.archive.org/web/20221220020247/https://medium.datadriveninvestor.com/javascript-promises-is-there-a-better-approach-dd6a0a329131 |url-status=live }}</ref> rather than on high-level descriptions of its expected results.


The term is often used in contrast to [[declarative programming]], which focuses on ''what'' the program should accomplish without specifying all the details of ''how'' the program should achieve the result.<ref>{{Cite web |title=Imperative programming: Overview of the oldest programming paradigm |url=https://www.ionos.com/digitalguide/websites/web-development/imperative-programming/ |access-date=2022-05-03 |website=IONOS Digitalguide |date=21 May 2021 |language=en |archive-date=2022-05-03 |archive-url=https://web.archive.org/web/20220503083342/https://www.ionos.com/digitalguide/websites/web-development/imperative-programming/ |url-status=live }}</ref>
The term is often used in contrast to [[declarative programming]], which focuses on ''what'' the program should accomplish without specifying all the details of ''how'' the program should achieve the result.<ref>{{Cite web |title=Imperative programming: Overview of the oldest programming paradigm |url=https://www.ionos.com/digitalguide/websites/web-development/imperative-programming/ |access-date=2022-05-03 |website=IONOS Digitalguide |date=21 May 2021 |language=en |archive-date=2022-05-03 |archive-url=https://web.archive.org/web/20220503083342/https://www.ionos.com/digitalguide/websites/web-development/imperative-programming/ |url-status=live }}</ref>
Line 11: Line 11:


==Rationale and foundations of imperative programming==
==Rationale and foundations of imperative programming==
The programming paradigm used to build programs for almost all computers typically follows an imperative model.<ref group=note>[[Reconfigurable computing]] is a notable exception.</ref> Digital computer hardware is designed to execute [[machine code]], which is native to the computer and is usually written in the imperative style, although low-level compilers and interpreters using other paradigms exist for some architectures such as [[lisp machine]]s.
The programming paradigm used to build programs for almost all computers typically follows an imperative model.<ref group=note>[[Reconfigurable computing]] is a notable exception.</ref> Digital computer hardware is designed to execute [[machine code]], which is native to the computer and is usually written in the imperative style, although low-level compilers and interpreters using other paradigms exist for some architectures such as [[Lisp machine]]s.


From this low-level perspective, the program state is defined by the contents of memory, and the statements are instructions in the native machine language of the computer. Higher-level imperative languages use [[variable (programming)|variable]]s and more complex statements, but still follow the same paradigm. [[Recipe]]s and process [[checklist]]s, while not [[computer program]]s, are also familiar concepts that are similar in style to imperative programming; each step is an instruction, and the physical world holds the state. Since the basic ideas of imperative programming are both conceptually familiar and directly embodied in the hardware, most computer languages are in the imperative style.
From this low-level perspective, the program state is defined by the contents of memory, and the statements are instructions in the native machine language of the computer. Higher-level imperative languages use [[variable (programming)|variable]]s and more complex statements, but still follow the same paradigm. [[Recipe]]s and process [[checklist]]s, while not [[computer program]]s, are also familiar concepts that are similar in style to imperative programming; each step is an instruction, and the physical world holds the state. Since the basic ideas of imperative programming are both conceptually familiar and directly embodied in the hardware, most computer languages are in the imperative style.
Line 22: Line 22:


==History of imperative and object-oriented languages==
==History of imperative and object-oriented languages==
The earliest imperative languages were the machine languages of the original computers. In these languages, instructions were very simple, which made hardware implementation easier but hindered the creation of complex programs. [[FORTRAN]], developed by [[John Backus]] at [[International Business Machines]] (IBM) starting in 1954, was the first major programming language to remove the obstacles presented by machine code in the creation of complex programs. FORTRAN was a [[compiled language]] that allowed named variables, complex expressions, subprograms, and many other features now common in imperative languages. The next two decades saw the development of many other major high-level imperative programming languages. In the late 1950s and 1960s, [[ALGOL]] was developed in order to allow mathematical algorithms to be more easily expressed and even served as the [[operating system]]'s target language for some computers. [[MUMPS]] (1966) carried the imperative paradigm to a logical extreme, by not having any statements at all, relying purely on commands, even to the extent of making the IF and ELSE commands independent of each other, connected only by an intrinsic variable named $TEST. [[COBOL]] (1960) and [[BASIC]] (1964) were both attempts to make programming syntax look more like English. In the 1970s, [[Pascal (programming language)|Pascal]] was developed by [[Niklaus Wirth]], and [[C (programming language)|C]] was created by [[Dennis Ritchie]] while he was working at [[Bell Laboratories]]. Wirth went on to design [[Modula-2]] and [[Oberon (programming language)|Oberon]]. For the needs of the [[United States Department of Defense]], [[Jean Ichbiah]] and a team at [[Honeywell]] began designing [[Ada (programming language)|Ada]] in 1978, after a 4-year project to define the requirements for the language. The specification was first published in 1983, with revisions in 1995, 2005, and 2012.
The earliest imperative languages were the machine languages of the original computers. In these languages, instructions were very simple, which made hardware implementation easier but hindered the creation of complex programs. [[Fortran]], developed by [[John Backus]] at [[International Business Machines]] (IBM) starting in 1954, was the first major programming language to remove the obstacles presented by machine code in the creation of complex programs. Fortran was a [[compiled language]] that allowed named variables, complex expressions, subprograms, and many other features now common in imperative languages. The next two decades saw the development of many other major high-level imperative programming languages. In the late 1950s and 1960s, [[ALGOL]] was developed in order to allow mathematical algorithms to be more easily expressed and even served as the [[operating system]]'s target language for some computers. [[MUMPS]] (1966) carried the imperative paradigm to a logical extreme, by not having any statements at all, relying purely on commands, even to the extent of making the IF and ELSE commands independent of each other, connected only by an intrinsic variable named $TEST. [[COBOL]] (1960) and [[BASIC]] (1964) were both attempts to make programming syntax look more like English. In the 1970s, [[Pascal (programming language)|Pascal]] was developed by [[Niklaus Wirth]], and [[C (programming language)|C]] was created by [[Dennis Ritchie]] while he was working at [[Bell Laboratories]]. Wirth went on to design [[Modula-2]] and [[Oberon (programming language)|Oberon]]. For the needs of the [[United States Department of Defense]], [[Jean Ichbiah]] and a team at [[Honeywell]] began designing [[Ada (programming language)|Ada]] in 1978, after a 4-year project to define the requirements for the language. The specification was first published in 1983, with revisions in 1995, 2005, and 2012.


The 1980s saw a rapid growth in interest in [[object-oriented programming]]. These languages were imperative in style, but added features to support [[object (computing)|objects]]. The last two decades of the 20th century saw the development of many such languages. [[Smalltalk]]-80, originally conceived by [[Alan Kay]] in 1969, was released in 1980, by the Xerox Palo Alto Research Center ([[PARC (company)|PARC]]). Drawing from concepts in another object-oriented language—[[Simula]] (which is considered the world's first [[object-oriented programming language]], developed in the 1960s)—[[Bjarne Stroustrup]] designed [[C++]], an object-oriented language based on [[C (programming language)|C]]. Design of [[C++]] began in 1979 and the first implementation was completed in 1983. In the late 1980s and 1990s, the notable imperative languages drawing on object-oriented concepts were [[Perl]], released by [[Larry Wall]] in 1987; [[Python (programming language)|Python]], released by [[Guido van Rossum]] in 1990; [[Visual Basic (classic)|Visual Basic]] and [[Visual C++]] (which included [[Microsoft Foundation Class Library]] (MFC) 2.0), released by [[Microsoft]] in 1991 and 1993 respectively; [[PHP]], released by [[Rasmus Lerdorf]] in 1994; [[Java (programming language)|Java]], by [[James Gosling]] ([[Sun Microsystems]]) in 1995, [[JavaScript]], by [[Brendan Eich]] ([[Netscape]]), and [[Ruby (programming language)|Ruby]], by Yukihiro "Matz" Matsumoto, both released in 1995. Microsoft's [[.NET Framework]] (2002) is imperative at its core, as are its main target languages, [[VB.NET]] and [[C Sharp (programming language)|C#]] that run on it; however Microsoft's [[F Sharp (programming language)|F#]], a functional language, also runs on it.
The 1980s saw a rapid growth in interest in [[object-oriented programming]]. These languages were imperative in style, but added features to support [[object (computing)|objects]]. The last two decades of the 20th century saw the development of many such languages. [[Smalltalk]]-80, originally conceived by [[Alan Kay]] in 1969, was released in 1980, by the Xerox Palo Alto Research Center ([[PARC (company)|PARC]]). Drawing from concepts in another object-oriented language—[[Simula]] (which is considered the world's first [[object-oriented programming language]], developed in the 1960s)—[[Bjarne Stroustrup]] designed [[C++]], an object-oriented language based on [[C (programming language)|C]]. Design of [[C++]] began in 1979 and the first implementation was completed in 1983. In the late 1980s and 1990s, the notable imperative languages drawing on object-oriented concepts were [[Perl]], released by [[Larry Wall]] in 1987; [[Python (programming language)|Python]], released by [[Guido van Rossum]] in 1990; [[Visual Basic (classic)|Visual Basic]] and [[Visual C++]] (which included [[Microsoft Foundation Class Library]] (MFC) 2.0), released by [[Microsoft]] in 1991 and 1993 respectively; [[PHP]], released by [[Rasmus Lerdorf]] in 1994; [[Java (programming language)|Java]], by [[James Gosling]] ([[Sun Microsystems]]) in 1995, [[JavaScript]], by [[Brendan Eich]] ([[Netscape]]), and [[Ruby (programming language)|Ruby]], by Yukihiro "Matz" Matsumoto, both released in 1995. Microsoft's [[.NET Framework]] (2002) is imperative at its core, as are its main target languages, [[VB.NET]] and [[C Sharp (programming language)|C#]] that run on it; however Microsoft's [[F Sharp (programming language)|F#]], a functional language, also runs on it.
Line 29: Line 29:


===Fortran===
===Fortran===
[[FORTRAN]] (1958) was unveiled as "The IBM Mathematical FORmula TRANslating system." It was designed for scientific calculations, without [[String (computer science)|string]] handling facilities. Along with [[Declaration (computer programming)|declarations]], [[Expression (computer science)|expressions]], and [[Statement (computer science)|statements]], it supported:
[[Fortran]] (1958) was unveiled as "The IBM Mathematical FORmula TRANslating system." It was designed for scientific calculations, without [[String (computer science)|string]] handling facilities. Along with [[Declaration (computer programming)|declarations]], [[Expression (computer science)|expressions]], and [[Statement (computer science)|statements]], it supported:
* [[Array data structure|arrays]]
* [[Array data structure|arrays]]
* [[subroutine]]s  
* [[subroutine]]s  
Line 47: Line 47:
}}</ref>
}}</ref>


However, non IBM vendors also wrote Fortran compilers, but with a syntax that would likely fail IBM's compiler.<ref name="cpl_3rd-ch2-16"/> The [[American National Standards Institute]] (ANSI) developed the first Fortran standard in 1966. In 1978, Fortran 77 became the standard until 1991. Fortran 90 supports:
However, non-IBM vendors also wrote Fortran compilers, but with a syntax that would likely fail IBM's compiler.<ref name="cpl_3rd-ch2-16"/> The [[American National Standards Institute]] (ANSI) developed the first Fortran standard in 1966. In 1978, Fortran 77 became the standard until 1991. Fortran 90 supports:
* [[Record (computer science)|records]]
* [[Record (computer science)|records]]
* [[Pointer (computer programming)|pointers]] to arrays
* [[Pointer (computer programming)|pointers]] to arrays
Line 72: Line 72:
COBOL's development was tightly controlled, so dialects did not emerge to require ANSI standards. As a consequence, it was not changed for 15 years until 1974. The 1990s version did make consequential changes, like [[object-oriented programming]].<ref name="cpl_3rd-ch2-25"/>
COBOL's development was tightly controlled, so dialects did not emerge to require ANSI standards. As a consequence, it was not changed for 15 years until 1974. The 1990s version did make consequential changes, like [[object-oriented programming]].<ref name="cpl_3rd-ch2-25"/>


===Algol===
===ALGOL===
[[ALGOL]] (1960) stands for "ALGOrithmic Language." It had a profound influence on programming language design.<ref name="cpl_3rd-ch2-19">{{cite book
[[ALGOL]] (1960) stands for "ALGOrithmic Language." It had a profound influence on programming language design.<ref name="cpl_3rd-ch2-19">{{cite book
   | last = Wilson
   | last = Wilson
Line 81: Line 81:
   | page = 19
   | page = 19
   | isbn = 0-201-71012-9
   | isbn = 0-201-71012-9
}}</ref> Emerging from a committee of European and American programming language experts, it used standard mathematical notation and had a readable structured design. Algol was first to define its [[Syntax (programming languages)|syntax]] using the [[Backus–Naur form]].<ref name="cpl_3rd-ch2-19"/> This led to [[Syntax-directed translation|syntax-directed]] compilers. It added features like:
}}</ref> Emerging from a committee of European and American programming language experts, it used standard mathematical notation and had a readable structured design. ALGOL was first to define its [[Syntax (programming languages)|syntax]] using the [[Backus–Naur form]].<ref name="cpl_3rd-ch2-19"/> This led to [[Syntax-directed translation|syntax-directed]] compilers. It added features like:
* block structure, where variables were local to their block
* block structure, where variables were local to their block
* arrays with variable bounds
* arrays with variable bounds
Line 88: Line 88:
* [[Recursion (computer science)|recursion]]<ref name="cpl_3rd-ch2-19"/>
* [[Recursion (computer science)|recursion]]<ref name="cpl_3rd-ch2-19"/>


Algol's direct descendants include [[Pascal (programming language)|Pascal]], [[Modula-2]], [[Ada (programming language)|Ada]], [[Delphi (software)|Delphi]] and [[Oberon (programming language)|Oberon]] on one branch. On another branch there's [[C (programming language)|C]], [[C++]] and [[Java (programming language)|Java]].<ref name="cpl_3rd-ch2-19"/>
ALGOL's direct descendants include [[Pascal (programming language)|Pascal]], [[Modula-2]], [[Ada (programming language)|Ada]], [[Delphi (software)|Delphi]] and [[Oberon (programming language)|Oberon]] on one branch. On another branch there's [[C (programming language)|C]], [[C++]] and [[Java (programming language)|Java]].<ref name="cpl_3rd-ch2-19"/>


===BASIC===
===BASIC===
Line 99: Line 99:
   | page = 30
   | page = 30
   | isbn = 0-201-71012-9
   | isbn = 0-201-71012-9
}}</ref> If a student did not go on to a more powerful language, the student would still remember Basic.<ref name="cpl_3rd-ch2-30"/> A Basic interpreter was installed in the [[microcomputers]] manufactured in the late 1970s. As the microcomputer industry grew, so did the language.<ref name="cpl_3rd-ch2-30"/>
}}</ref> If a student did not go on to a more powerful language, the student would still remember BASIC.<ref name="cpl_3rd-ch2-30"/> A BASIC interpreter was installed in the [[microcomputers]] manufactured in the late 1970s. As the microcomputer industry grew, so did the language.<ref name="cpl_3rd-ch2-30"/>


Basic pioneered the [[Read–eval–print loop|interactive session]].<ref name="cpl_3rd-ch2-30"/> It offered [[operating system]] commands within its environment:
BASIC pioneered the [[Read–eval–print loop|interactive session]].<ref name="cpl_3rd-ch2-30"/> It offered [[operating system]] commands within its environment:
* The 'new' command created an empty slate
* The 'new' command created an empty slate
* Statements evaluated immediately
* Statements evaluated immediately
Line 108: Line 108:
* The 'run' command executed the program
* The 'run' command executed the program


However, the Basic syntax was too simple for large programs.<ref name="cpl_3rd-ch2-30"/> Recent dialects added structure and object-oriented extensions. [[Microsoft|Microsoft's]] [[Visual Basic]] is still widely used and produces a [[graphical user interface]].<ref name="cpl_3rd-ch2-31">{{cite book
However, the BASIC syntax was too simple for large programs.<ref name="cpl_3rd-ch2-30"/> Recent dialects added structure and object-oriented extensions. [[Microsoft|Microsoft's]] [[Visual Basic]] is still widely used and produces a [[graphical user interface]].<ref name="cpl_3rd-ch2-31">{{cite book
   | last = Wilson
   | last = Wilson
   | first = Leslie B.
   | first = Leslie B.
Line 138: Line 138:


* The ''global and static data'' region is located just above the ''program'' region. (The program region is technically called the ''text'' region. It's where machine instructions are stored.)
* The ''global and static data'' region is located just above the ''program'' region. (The program region is technically called the ''text'' region. It's where machine instructions are stored.)
:* The global and static data region is technically two regions.<ref name="geeksforgeeks">{{cite web
** The global and static data region is technically two regions.<ref name="geeksforgeeks">{{cite web
| url = https://www.geeksforgeeks.org/memory-layout-of-c-program/
| url = https://www.geeksforgeeks.org/memory-layout-of-c-program/
| title = Memory Layout of C Programs
| title = Memory Layout of C Programs
Line 147: Line 147:
| url-status = live
| url-status = live
}}</ref> One region is called the ''initialized [[data segment]]'', where variables declared with default values are stored. The other region is called the ''[[.bss|block started by segment]]'', where variables declared without default values are stored.
}}</ref> One region is called the ''initialized [[data segment]]'', where variables declared with default values are stored. The other region is called the ''[[.bss|block started by segment]]'', where variables declared without default values are stored.
:* Variables stored in the ''global and static data'' region have their [[Memory address|addresses]] set at compile-time. They retain their values throughout the life of the process.
** Variables stored in the ''global and static data'' region have their [[Memory address|addresses]] set at compile-time. They retain their values throughout the life of the process.
 
** The global and static region stores the ''global variables'' that are declared on top of (outside) the <code>main()</code> function.<ref name="cpl-ch1-p31">{{cite book
:* The global and static region stores the ''global variables'' that are declared on top of (outside) the <code>main()</code> function.<ref name="cpl-ch1-p31">{{cite book
  |title=The C Programming Language Second Edition
  |title=The C Programming Language Second Edition
  |last1=Kernighan
  |last1=Kernighan
Line 159: Line 158:
  |isbn=0-13-110362-8
  |isbn=0-13-110362-8
  |page=31}}</ref> Global variables are visible to <code>main()</code> and every other function in the source code.
  |page=31}}</ref> Global variables are visible to <code>main()</code> and every other function in the source code.
 
* On the other hand, variable declarations inside of <code>main()</code>, other functions, or within <code>{</code> <code>}</code> [[Block (programming)|block delimiters]] are ''local variables''. Local variables also include ''[[Parameter (computer programming)#Parameters and arguments|formal parameter]] variables''. Parameter variables are enclosed within the parenthesis of function definitions.<ref name="cpl_3rd-ch6-128">{{cite book
: On the other hand, variable declarations inside of <code>main()</code>, other functions, or within <code>{</code> <code>}</code> [[Block (programming)|block delimiters]] are ''local variables''. Local variables also include ''[[Parameter (computer programming)#Parameters and arguments|formal parameter]] variables''. Parameter variables are enclosed within the parenthesis of function definitions.<ref name="cpl_3rd-ch6-128">{{cite book
   | last = Wilson
   | last = Wilson
   | first = Leslie B.
   | first = Leslie B.
Line 169: Line 167:
   | isbn = 0-201-71012-9
   | isbn = 0-201-71012-9
}}</ref> They provide an [[Interface (computing)|interface]] to the function.
}}</ref> They provide an [[Interface (computing)|interface]] to the function.
 
** ''Local variables'' declared using the <code>static</code> prefix are also stored in the ''global and static data'' region.<ref name="geeksforgeeks"/> Unlike global variables, static variables are only visible within the function or block. Static variables always retain their value. An example usage would be the function  
:* ''Local variables'' declared using the <code>static</code> prefix are also stored in the ''global and static data'' region.<ref name="geeksforgeeks"/> Unlike global variables, static variables are only visible within the function or block. Static variables always retain their value. An example usage would be the function <code>int increment_counter(){ static int counter = 0; counter++; return counter;}</code>
**: {{sxhl|2=c|1=
 
int increment_counter() {
    static int counter = 0;
    counter++;  
    return counter;
}
}}
* The [[call stack|stack]] region is a contiguous block of memory located near the top memory address.<ref name="lpi-ch6-p121">{{cite book
* The [[call stack|stack]] region is a contiguous block of memory located near the top memory address.<ref name="lpi-ch6-p121">{{cite book
  |title=The Linux Programming Interface
  |title=The Linux Programming Interface
Line 180: Line 183:
  |isbn=978-1-59327-220-3
  |isbn=978-1-59327-220-3
  |page=121}}</ref> Variables placed in the stack are populated from top to bottom.<ref name="lpi-ch6-p121"/> A [[Call stack#STACK-POINTER|stack pointer]] is a special-purpose [[processor register|register]] that keeps track of the last memory address populated.<ref name="lpi-ch6-p121"/> Variables are placed into the stack via the ''assembly language'' PUSH instruction. Therefore, the addresses of these variables are set during [[Runtime (program lifecycle phase)|runtime]]. The method for stack variables to lose their [[Scope (computer science)|scope]] is via the POP instruction.
  |page=121}}</ref> Variables placed in the stack are populated from top to bottom.<ref name="lpi-ch6-p121"/> A [[Call stack#STACK-POINTER|stack pointer]] is a special-purpose [[processor register|register]] that keeps track of the last memory address populated.<ref name="lpi-ch6-p121"/> Variables are placed into the stack via the ''assembly language'' PUSH instruction. Therefore, the addresses of these variables are set during [[Runtime (program lifecycle phase)|runtime]]. The method for stack variables to lose their [[Scope (computer science)|scope]] is via the POP instruction.
 
** ''Local variables'' declared without the <code>static</code> prefix, including formal parameter variables,<ref name="lpi-ch6-p122">{{cite book
:* ''Local variables'' declared without the <code>static</code> prefix, including formal parameter variables,<ref name="lpi-ch6-p122">{{cite book
  |title=The Linux Programming Interface
  |title=The Linux Programming Interface
  |last=Kerrisk
  |last=Kerrisk
Line 189: Line 191:
  |isbn=978-1-59327-220-3
  |isbn=978-1-59327-220-3
  |page=122}}</ref> are called ''automatic variables''<ref name="cpl-ch1-p31"/> and are stored in the stack.<ref name="geeksforgeeks"/> They are visible inside the function or block and lose their scope upon exiting the function or block.
  |page=122}}</ref> are called ''automatic variables''<ref name="cpl-ch1-p31"/> and are stored in the stack.<ref name="geeksforgeeks"/> They are visible inside the function or block and lose their scope upon exiting the function or block.
 
** The [[Manual memory management|heap]] region is located below the stack.<ref name="geeksforgeeks"/> It is populated from the bottom to the top. The [[operating system]] manages the heap using a ''heap pointer'' and a list of allocated memory blocks.<ref name="cpl-ch1-p185">{{cite book
* The [[Manual memory management|heap]] region is located below the stack.<ref name="geeksforgeeks"/> It is populated from the bottom to the top. The [[operating system]] manages the heap using a ''heap pointer'' and a list of allocated memory blocks.<ref name="cpl-ch1-p185">{{cite book
  |title=The C Programming Language Second Edition
  |title=The C Programming Language Second Edition
  |last1=Kernighan
  |last1=Kernighan
Line 200: Line 201:
  |isbn=0-13-110362-8
  |isbn=0-13-110362-8
  |page=185}}</ref> Like the stack, the addresses of heap variables are set during runtime. An [[out of memory]] error occurs when the heap pointer and the stack pointer meet.
  |page=185}}</ref> Like the stack, the addresses of heap variables are set during runtime. An [[out of memory]] error occurs when the heap pointer and the stack pointer meet.
 
** ''C'' provides the <code>malloc()</code> library function to [[C dynamic memory allocation|allocate]] heap memory.<ref name="cpl-ch8-p187">{{cite book
:* ''C'' provides the <code>malloc()</code> library function to [[C dynamic memory allocation|allocate]] heap memory.<ref name="cpl-ch8-p187">{{cite book
  |title=The C Programming Language Second Edition
  |title=The C Programming Language Second Edition
  |last1=Kernighan
  |last1=Kernighan
Line 231: Line 231:
}}</ref> Abstract datatypes are [[Record (computer science)|structures]] of concrete datatypes — with a new name assigned. For example, a [[List (abstract data type)|list]] of integers could be called <code>integer_list</code>.
}}</ref> Abstract datatypes are [[Record (computer science)|structures]] of concrete datatypes — with a new name assigned. For example, a [[List (abstract data type)|list]] of integers could be called <code>integer_list</code>.


In object-oriented jargon, abstract datatypes are called [[Class (computer programming)|classes]]. However, a ''class'' is only a definition; no memory is allocated. When memory is allocated to a class, it's called an [[Object (computer science)|object]].<ref name="cpl_3rd-ch8-193">{{cite book
In object-oriented jargon, abstract datatypes are called [[Class (programming)|classes]]. However, a ''class'' is only a definition; no memory is allocated. When memory is allocated to a class, it's called an [[Object (computer science)|object]].<ref name="cpl_3rd-ch8-193">{{cite book
   | last = Wilson
   | last = Wilson
   | first = Leslie B.
   | first = Leslie B.
Line 500: Line 500:


==See also==
==See also==
{{Columns-list|colwidth=22em|
<!--♦♦♦ Please keep the list in alphabetical order ♦♦♦-->
* [[Functional programming]]
* [[Functional programming]]
* [[Reactive programming]]
* [[History of programming languages]]
* [[History of programming languages]]
* [[List of programming languages by category#Imperative languages|List of imperative programming languages]]
* [[List of programming languages by category#Imperative languages|List of imperative programming languages]]
* [[Reactive programming]]
* [[Side effect (computer science)]]
}}


==Notes==
==Notes==
Line 519: Line 525:
{{Programming paradigms navbox}}
{{Programming paradigms navbox}}
{{Types of programming languages}}
{{Types of programming languages}}
{{Authority control}}
{{Authority control}}


{{DEFAULTSORT:Imperative Programming}}
{{DEFAULTSORT:Imperative Programming}}
<!--Categories-->
 
[[Category:Programming paradigms]]
[[Category:Programming paradigms]]
[[Category:Programming language comparisons]]
<!-- Hidden categories below -->
[[Category:Articles with example C++ code]]

Latest revision as of 03:46, 29 December 2025

Template:Short description Script error: No such module "Unsubst". In computer science, imperative programming is a programming paradigm of software that uses statements that change a process' state. In much the same way that the imperative mood in natural languages expresses commands, an imperative program consists of commands for the computer to perform. Imperative programming focuses on describing how a program operates step by step (with general order of the steps being determined in source code by the placement of statements one below the other),[1] rather than on high-level descriptions of its expected results.

The term is often used in contrast to declarative programming, which focuses on what the program should accomplish without specifying all the details of how the program should achieve the result.[2]

Procedural programming

Procedural programming is a type of imperative programming in which the program is built from one or more procedures (also termed subroutines or functions). The terms are often used as synonyms, but the use of procedures has a dramatic effect on how imperative programs appear and how they are constructed. Heavy procedural programming, in which state changes are localized to procedures or restricted to explicit arguments and returns from procedures, is a form of structured programming. Since the 1960s, structured programming and modular programming in general have been promoted as techniques to improve the maintainability and overall quality of imperative programs. The concepts behind object-oriented programming attempt to extend this approach.

Procedural programming could be considered a step toward declarative programming. A programmer can often tell, simply by looking at the names, arguments, and return types of procedures (and related comments), what a particular procedure is supposed to do, without necessarily looking at the details of how it achieves its result. At the same time, a complete program is still imperative since it fixes the statements to be executed and their order of execution to a large extent.

Rationale and foundations of imperative programming

The programming paradigm used to build programs for almost all computers typically follows an imperative model.[note 1] Digital computer hardware is designed to execute machine code, which is native to the computer and is usually written in the imperative style, although low-level compilers and interpreters using other paradigms exist for some architectures such as Lisp machines.

From this low-level perspective, the program state is defined by the contents of memory, and the statements are instructions in the native machine language of the computer. Higher-level imperative languages use variables and more complex statements, but still follow the same paradigm. Recipes and process checklists, while not computer programs, are also familiar concepts that are similar in style to imperative programming; each step is an instruction, and the physical world holds the state. Since the basic ideas of imperative programming are both conceptually familiar and directly embodied in the hardware, most computer languages are in the imperative style.

Assignment statements, in imperative paradigm, perform an operation on information located in memory and store the results in memory for later use. High-level imperative languages, in addition, permit the evaluation of complex expressions, which may consist of a combination of arithmetic operations and function evaluations, and the assignment of the resulting value to memory. Looping statements (as in while loops, do while loops, and for loops) allow a sequence of statements to be executed multiple times. Loops can either execute the statements they contain a predefined number of times, or they can execute them repeatedly until some condition is met. Conditional branching statements allow a sequence of statements to be executed only if some condition is met. Otherwise, the statements are skipped and the execution sequence continues from the statement following them. Unconditional branching statements allow an execution sequence to be transferred to another part of a program. These include the jump (called goto in many languages), switch, and the subprogram, subroutine, or procedure call (which usually returns to the next statement after the call).

Early in the development of high-level programming languages, the introduction of the block enabled the construction of programs in which a group of statements and declarations could be treated as if they were one statement. This, alongside the introduction of subroutines, enabled complex structures to be expressed by hierarchical decomposition into simpler procedural structures.

Many imperative programming languages (such as Fortran, BASIC, and C) are abstractions of assembly language.[3]

History of imperative and object-oriented languages

The earliest imperative languages were the machine languages of the original computers. In these languages, instructions were very simple, which made hardware implementation easier but hindered the creation of complex programs. Fortran, developed by John Backus at International Business Machines (IBM) starting in 1954, was the first major programming language to remove the obstacles presented by machine code in the creation of complex programs. Fortran was a compiled language that allowed named variables, complex expressions, subprograms, and many other features now common in imperative languages. The next two decades saw the development of many other major high-level imperative programming languages. In the late 1950s and 1960s, ALGOL was developed in order to allow mathematical algorithms to be more easily expressed and even served as the operating system's target language for some computers. MUMPS (1966) carried the imperative paradigm to a logical extreme, by not having any statements at all, relying purely on commands, even to the extent of making the IF and ELSE commands independent of each other, connected only by an intrinsic variable named $TEST. COBOL (1960) and BASIC (1964) were both attempts to make programming syntax look more like English. In the 1970s, Pascal was developed by Niklaus Wirth, and C was created by Dennis Ritchie while he was working at Bell Laboratories. Wirth went on to design Modula-2 and Oberon. For the needs of the United States Department of Defense, Jean Ichbiah and a team at Honeywell began designing Ada in 1978, after a 4-year project to define the requirements for the language. The specification was first published in 1983, with revisions in 1995, 2005, and 2012.

The 1980s saw a rapid growth in interest in object-oriented programming. These languages were imperative in style, but added features to support objects. The last two decades of the 20th century saw the development of many such languages. Smalltalk-80, originally conceived by Alan Kay in 1969, was released in 1980, by the Xerox Palo Alto Research Center (PARC). Drawing from concepts in another object-oriented language—Simula (which is considered the world's first object-oriented programming language, developed in the 1960s)—Bjarne Stroustrup designed C++, an object-oriented language based on C. Design of C++ began in 1979 and the first implementation was completed in 1983. In the late 1980s and 1990s, the notable imperative languages drawing on object-oriented concepts were Perl, released by Larry Wall in 1987; Python, released by Guido van Rossum in 1990; Visual Basic and Visual C++ (which included Microsoft Foundation Class Library (MFC) 2.0), released by Microsoft in 1991 and 1993 respectively; PHP, released by Rasmus Lerdorf in 1994; Java, by James Gosling (Sun Microsystems) in 1995, JavaScript, by Brendan Eich (Netscape), and Ruby, by Yukihiro "Matz" Matsumoto, both released in 1995. Microsoft's .NET Framework (2002) is imperative at its core, as are its main target languages, VB.NET and C# that run on it; however Microsoft's F#, a functional language, also runs on it.

Examples

Fortran

Fortran (1958) was unveiled as "The IBM Mathematical FORmula TRANslating system." It was designed for scientific calculations, without string handling facilities. Along with declarations, expressions, and statements, it supported:

It succeeded because:

  • programming and debugging costs were below computer running costs
  • it was supported by IBM
  • applications at the time were scientific.[4]

However, non-IBM vendors also wrote Fortran compilers, but with a syntax that would likely fail IBM's compiler.[4] The American National Standards Institute (ANSI) developed the first Fortran standard in 1966. In 1978, Fortran 77 became the standard until 1991. Fortran 90 supports:

COBOL

COBOL (1959) stands for "COmmon Business Oriented Language." Fortran manipulated symbols. It was soon realized that symbols did not need to be numbers, so strings were introduced.[5] The US Department of Defense influenced COBOL's development, with Grace Hopper being a major contributor. The statements were English-like and verbose. The goal was to design a language so managers could read the programs. However, the lack of structured statements hindered this goal.[6]

COBOL's development was tightly controlled, so dialects did not emerge to require ANSI standards. As a consequence, it was not changed for 15 years until 1974. The 1990s version did make consequential changes, like object-oriented programming.[6]

ALGOL

ALGOL (1960) stands for "ALGOrithmic Language." It had a profound influence on programming language design.[7] Emerging from a committee of European and American programming language experts, it used standard mathematical notation and had a readable structured design. ALGOL was first to define its syntax using the Backus–Naur form.[7] This led to syntax-directed compilers. It added features like:

ALGOL's direct descendants include Pascal, Modula-2, Ada, Delphi and Oberon on one branch. On another branch there's C, C++ and Java.[7]

BASIC

BASIC (1964) stands for "Beginner's All Purpose Symbolic Instruction Code." It was developed at Dartmouth College for all of their students to learn.[8] If a student did not go on to a more powerful language, the student would still remember BASIC.[8] A BASIC interpreter was installed in the microcomputers manufactured in the late 1970s. As the microcomputer industry grew, so did the language.[8]

BASIC pioneered the interactive session.[8] It offered operating system commands within its environment:

  • The 'new' command created an empty slate
  • Statements evaluated immediately
  • Statements could be programmed by preceding them with a line number
  • The 'list' command displayed the program
  • The 'run' command executed the program

However, the BASIC syntax was too simple for large programs.[8] Recent dialects added structure and object-oriented extensions. Microsoft's Visual Basic is still widely used and produces a graphical user interface.[9]

C

C programming language (1973) got its name because the language BCPL was replaced with B, and AT&T Bell Labs called the next version "C." Its purpose was to write the UNIX operating system.[10] C is a relatively small language -- making it easy to write compilers. Its growth mirrored the hardware growth in the 1980s.[10] Its growth also was because it has the facilities of assembly language, but uses a high-level syntax. It added advanced features like:

File:Computer-memory-map.png
Computer memory map

C allows the programmer to control in which region of memory data is to be stored. Global variables and static variables require the fewest clock cycles to store. The stack is automatically used for the standard variable declarations. Heap memory is returned to a pointer variable from the malloc() function.

  • The global and static data region is located just above the program region. (The program region is technically called the text region. It's where machine instructions are stored.)
    • The global and static data region is technically two regions.[11] One region is called the initialized data segment, where variables declared with default values are stored. The other region is called the block started by segment, where variables declared without default values are stored.
    • Variables stored in the global and static data region have their addresses set at compile-time. They retain their values throughout the life of the process.
    • The global and static region stores the global variables that are declared on top of (outside) the main() function.[12] Global variables are visible to main() and every other function in the source code.
  • On the other hand, variable declarations inside of main(), other functions, or within { } block delimiters are local variables. Local variables also include formal parameter variables. Parameter variables are enclosed within the parenthesis of function definitions.[13] They provide an interface to the function.
    • Local variables declared using the static prefix are also stored in the global and static data region.[11] Unlike global variables, static variables are only visible within the function or block. Static variables always retain their value. An example usage would be the function
      Template:Sxhl
  • The stack region is a contiguous block of memory located near the top memory address.[14] Variables placed in the stack are populated from top to bottom.[14] A stack pointer is a special-purpose register that keeps track of the last memory address populated.[14] Variables are placed into the stack via the assembly language PUSH instruction. Therefore, the addresses of these variables are set during runtime. The method for stack variables to lose their scope is via the POP instruction.
    • Local variables declared without the static prefix, including formal parameter variables,[15] are called automatic variables[12] and are stored in the stack.[11] They are visible inside the function or block and lose their scope upon exiting the function or block.
    • The heap region is located below the stack.[11] It is populated from the bottom to the top. The operating system manages the heap using a heap pointer and a list of allocated memory blocks.[16] Like the stack, the addresses of heap variables are set during runtime. An out of memory error occurs when the heap pointer and the stack pointer meet.
    • C provides the malloc() library function to allocate heap memory.[17] Populating the heap with data is an additional copy function. Variables stored in the heap are economically passed to functions using pointers. Without pointers, the entire block of data would have to be passed to the function via the stack.

C++

In the 1970s, software engineers needed language support to break large projects down into modules.[18] One obvious feature was to decompose large projects physically into separate files. A less obvious feature was to decompose large projects logically into abstract datatypes.[18] At the time, languages supported concrete (scalar) datatypes like integer numbers, floating-point numbers, and strings of characters. Concrete datatypes have their representation as part of their name.[19] Abstract datatypes are structures of concrete datatypes — with a new name assigned. For example, a list of integers could be called integer_list.

In object-oriented jargon, abstract datatypes are called classes. However, a class is only a definition; no memory is allocated. When memory is allocated to a class, it's called an object.[20]

Object-oriented imperative languages developed by combining the need for classes and the need for safe functional programming.[21] A function, in an object-oriented language, is assigned to a class. An assigned function is then referred to as a method, member function, or operation. Object-oriented programming is executing operations on objects.[22]

Object-oriented languages support a syntax to model subset/superset relationships. In set theory, an element of a subset inherits all the attributes contained in the superset. For example, a student is a person. Therefore, the set of students is a subset of the set of persons. As a result, students inherit all the attributes common to all persons. Additionally, students have unique attributes that other persons don't have. Object-oriented languages model subset/superset relationships using inheritance.[23] Object-oriented programming became the dominant language paradigm by the late 1990s.[18]

C++ (1985) was originally called "C with Classes."[24] It was designed to expand C's capabilities by adding the object-oriented facilities of the language Simula.[25]

An object-oriented module is composed of two files. The definitions file is called the header file. Here is a C++ header file for the GRADE class in a simple school application:

// grade.h
// -------

// Used to allow multiple source files to include
// this header file without duplication errors.
// See: https://en.wikipedia.org/wiki/Include_guard
// ----------------------------------------------
#ifndef GRADE_H
#define GRADE_H

class GRADE {
public:
    // This is the constructor operation.
    // ----------------------------------
    GRADE ( const char letter );

    // This is a class variable.
    // -------------------------
    char letter;

    // This is a member operation.
    // ---------------------------
    int grade_numeric( const char letter );

    // This is a class variable.
    // -------------------------
    int numeric;
};
#endif

A constructor operation is a function with the same name as the class name.[26] It is executed when the calling operation executes the new statement.

A module's other file is the source file. Here is a C++ source file for the GRADE class in a simple school application:

// grade.cpp
// ---------
#include "grade.h"

GRADE::GRADE( const char letter )
{
    // Reference the object using the keyword 'this'.
    // ----------------------------------------------
    this->letter = letter;

    // This is Temporal Cohesion
    // -------------------------
    this->numeric = grade_numeric( letter );
}

int GRADE::grade_numeric( const char letter )
{
    if ( ( letter == 'A' || letter == 'a' ) )
        return 4;
    else
    if ( ( letter == 'B' || letter == 'b' ) )
        return 3;
    else
    if ( ( letter == 'C' || letter == 'c' ) )
        return 2;
    else
    if ( ( letter == 'D' || letter == 'd' ) )
        return 1;
    else
    if ( ( letter == 'F' || letter == 'f' ) )
        return 0;
    else
        return -1;
}

Here is a C++ header file for the PERSON class in a simple school application:

// person.h
// --------
#ifndef PERSON_H
#define PERSON_H

class PERSON {
public:
    PERSON ( const char *name );
    const char *name;
};
#endif

Here is a C++ source file for the PERSON class in a simple school application:

// person.cpp
// ----------
#include "person.h"

PERSON::PERSON ( const char *name )
{
    this->name = name;
}

Here is a C++ header file for the STUDENT class in a simple school application:

// student.h
// ---------
#ifndef STUDENT_H
#define STUDENT_H

#include "person.h"
#include "grade.h"

// A STUDENT is a subset of PERSON.
// --------------------------------
class STUDENT : public PERSON{
public:
    STUDENT ( const char *name );
    ~STUDENT();
    GRADE *grade;
};
#endif

Here is a C++ source file for the STUDENT class in a simple school application:

// student.cpp
// -----------
#include "student.h"
#include "person.h"

STUDENT::STUDENT ( const char *name ):
    // Execute the constructor of the PERSON superclass.
    // -------------------------------------------------
    PERSON( name )
{
    // Nothing else to do.
    // -------------------
}

STUDENT::~STUDENT() 
{
    // deallocate grade's memory
    // to avoid memory leaks.
    // -------------------------------------------------
    delete this->grade;
}

Here is a driver program for demonstration:

// student_dvr.cpp
// ---------------
#include <iostream>
#include "student.h"

int main( void )
{
    STUDENT *student = new STUDENT( "The Student" );
    student->grade = new GRADE( 'a' );

    std::cout 
        // Notice student inherits PERSON's name
        << student->name
        << ": Numeric grade = "
        << student->grade->numeric
        << "\n";

    // deallocate student's memory
    // to avoid memory leaks.
    // -------------------------------------------------
    delete student;

	return 0;
}

Here is a makefile to compile everything:

# makefile
# --------
all: student_dvr

clean:
    rm student_dvr *.o

student_dvr: student_dvr.cpp grade.o student.o person.o
    c++ student_dvr.cpp grade.o student.o person.o -o student_dvr

grade.o: grade.cpp grade.h
    c++ -c grade.cpp

student.o: student.cpp student.h
    c++ -c student.cpp

person.o: person.cpp person.h
    c++ -c person.cpp

See also

Script error: No such module "Template wrapper".Script error: No such module "Check for unknown parameters".

Notes

<templatestyles src="Reflist/styles.css" />

  1. Reconfigurable computing is a notable exception.

Script error: No such module "Check for unknown parameters".

References

<templatestyles src="Reflist/styles.css" />

  1. Script error: No such module "citation/CS1".
  2. Script error: No such module "citation/CS1".
  3. Script error: No such module "citation/CS1".
  4. a b Script error: No such module "citation/CS1".
  5. Script error: No such module "citation/CS1".
  6. a b Script error: No such module "citation/CS1".
  7. a b c d Script error: No such module "citation/CS1".
  8. a b c d e Script error: No such module "citation/CS1".
  9. Script error: No such module "citation/CS1".
  10. a b c Script error: No such module "citation/CS1".
  11. a b c d Script error: No such module "citation/CS1".
  12. a b Script error: No such module "citation/CS1".
  13. Script error: No such module "citation/CS1".
  14. a b c Script error: No such module "citation/CS1".
  15. Script error: No such module "citation/CS1".
  16. Script error: No such module "citation/CS1".
  17. Script error: No such module "citation/CS1".
  18. a b c Script error: No such module "citation/CS1".
  19. Script error: No such module "citation/CS1".
  20. Script error: No such module "citation/CS1".
  21. Script error: No such module "citation/CS1".
  22. Script error: No such module "citation/CS1".
  23. Script error: No such module "citation/CS1".
  24. Script error: No such module "citation/CS1".
  25. Script error: No such module "citation/CS1".
  26. Script error: No such module "citation/CS1".

Script error: No such module "Check for unknown parameters".

  • Pratt, Terrence W. and Marvin V. Zelkowitz. Programming Languages: Design and Implementation, 3rd ed. Englewood Cliffs, N.J.: Prentice Hall, 1996.
  • Sebesta, Robert W. Concepts of Programming Languages, 3rd ed. Reading, Mass.: Addison-Wesley Publishing Company, 1996.
Originally based on the article 'Imperative programming' by Stan Seibert, from Nupedia, licensed under the GNU Free Documentation License.

Template:Programming paradigms navbox Script error: No such module "Navbox". Template:Authority control