Posts

Showing posts from August, 2023

Alternative to exceptions when attempting to pop an empty stack

  A recent question on StackOverflow asked about whether or not a mutex is locked twice by the same thread without unlocking the mutex. See https://stackoverflow.com/questions/76890110/c-the-thread-repeatedly-locks-the-same-mutex-multiple-times?noredirect=1#comment135552146_76890110 The C++ source code presented in the question is: 1 #include <exception> 2 #include <memory> 3 #include <mutex> 4 #include <stack> 5 6 struct empty_stack : std :: exception 7 { 8     const char * what () const throw (); 9 }; 10 11 template < typename T > 12 class threadsafe_stack 13 { 14 private : 15     std :: stack < T > data ; 16     mutable std :: mutex m ; 17 public : 18     threadsafe_stack (){} 19     threadsafe_stack ( const threadsafe_stack & other ) { 20        std :: lock_guard < std :: mutex > lock ( other . m ); 21    ...

Variant Records used as a return type from search functions

 When searching for a value in an array a programmer is faced with two possibilities. 1.        The value searched for is found and the index of the value in the array is returned. 2.        The value is not found and no array index is returned. It is common practice to return a scalar value from functions using the C programming language. This tradition goes back to the earliest days of the C language when unspecified function return types were given the int type by default by the compiler. The C language does not have a concept of exceptions or exception handlers. Instead, the value returned by a function either indicates success or failure. It is common for positive return values to indicate success and negative or zero values to indicate failure. This pattern was established by the Unix operating system. C was invented to write the Unix operating system. A search function is often designed to return the ind...

Array Handling

  Arrays in both C and Ada are a compound type with the elements arranged sequentially in memory. All the elements in an array are of a single type. For instance an array may contain integer elements or it may contain floating point elements, or it may contain strings of characters, or it may even contain other arrays. One might therefore assume that arrays in C and Ada are fundamentally the same. This article explores that assumption and finds some clear differences between C arrays and Ada arrays. Array Characteristic C language Ada Language Array types C only allows definition of the type of an array element. It does not allow declaration of an array type. Every Ada array is a member of a type, even if it is an anonymous type. Index range Valid C array indices always start at 0. The C language provides no implicit checking for referencing invalid array indices. Ada array indices may...