Assertions: Difference between revisions
(added c) |
(Ada solution added) |
||
Line 3: | Line 3: | ||
Show an assertion in your language by asserting that an integer variable is equal to 42. |
Show an assertion in your language by asserting that an integer variable is equal to 42. |
||
=={{header|Ada}}== |
|||
Using pragma Assert: |
|||
<lang ada> |
|||
pragma Assert (A = 42, "Oops!"); |
|||
</lang> |
|||
The behavior of pragma is controlled by pragma Assertion_Policy. Another way is to use the predefined package Ada.Assertions: |
|||
<lang ada> |
|||
with Ada.Assertions; use Ada.Assertions; |
|||
... |
|||
Assert (A = 42, "Oops!"); |
|||
</lang> |
|||
The procedure Assert propagates Assertion_Error when condition is false. |
|||
=={{header|C}}== |
=={{header|C}}== |
||
<lang c>#include <assert.h> |
<lang c>#include <assert.h> |
Revision as of 08:55, 4 February 2009
You are encouraged to solve this task according to the task description, using any language you may know.
Assertions are a way of breaking out of code when there is an error or an unexpected input. Some languages throw exceptions and some treat it as a break point.
Show an assertion in your language by asserting that an integer variable is equal to 42.
Ada
Using pragma Assert: <lang ada> pragma Assert (A = 42, "Oops!"); </lang> The behavior of pragma is controlled by pragma Assertion_Policy. Another way is to use the predefined package Ada.Assertions: <lang ada> with Ada.Assertions; use Ada.Assertions; ... Assert (A = 42, "Oops!"); </lang> The procedure Assert propagates Assertion_Error when condition is false.
C
<lang c>#include <assert.h>
int main(){
int a; /* ...input or change a here */ assert(a == 42); /* aborts program when a is not 42 */
return 0;
}</lang>
Java
<lang java5>public static void main(String[] args){
int a; //...input or change a here assert a == 42;//throws an AssertionError when a is not 42 assert a == 42 : "Error message"; //throws an AssertionError //when a is not 42 with "Error message" for the message //the error message can be any non-void expression
}</lang>
Python
<lang python>a = 5
- ...input or change a here
assert a == 42 # throws an AssertionError when a is not 42 assert a == 42, "Error message" # throws an AssertionError
# when a is not 42 with "Error message" for the message # the error message can be any expression</lang>