Posts Tagged ‘gotcha’

Bash gotcha: function variable scope

Posted: 11th October 2015 by Tim in Bash, Linux
Tags: , , , , , , ,

Consider the following bash script: #!/usr/bin/env bash function myFunc {     myvar=123     echo “myFunc: setting myvar=$myvar” } myvar=1 echo “before myFunc: myvar=$myvar” myFunc echo “after myFunc: myvar=$myvar” The code here is fairly simple – we set a variable myvar, call a function and print the value of myvar to the terminal. However, even though we don’t […]

Consider the following query (tested on PostgreSQL – some other systems may require a table to be specified): SELECT ‘Yes’ AS Value_Returned WHERE 1 != 2; This query returns 1 row: ( Value_Returned = ‘Yes’ ), as one would expect. But what if we compare against NULL? SELECT ‘Yes’ AS Value_Returned WHERE 1 != NULL; […]

C/C++ gotcha – using #if true

Posted: 14th April 2014 by Tim in C, C++
Tags: , , , , , , ,

Consider the following code, which compiles without warnings with both gcc and g++: #include <stdio.h> int main(int argc, char **argv) { #if true     printf(“This does what you expect\n”); #else     printf(“This does not do what you expect!\n”); #endif     return 0; } When compiling with g++, the program prints This does what you expect. However, when compiling […]

C/C++ gotcha – ternary operator casting

Posted: 13th January 2014 by Tim in C, C++
Tags: , , , , , ,

C and C++ have what is known as a ternary operator; syntax which allows you to do conditional operations inline. This is done using syntax similar to: const int b = (<condition> ? 10 : 100); This will set b to 10 if <condition> is true, or 100 otherwise. Ternary operators allow code to be […]

C and C++ code is generally pretty easy to make sense of. But there are a few oddities which can catch you out and can send you into an endless debugging exercise if you’re not careful. One such oddity is conditional evaluation. Consider the following code which keeps track of three numbers. Look through the […]

C++ can be a strange language. Most of the time it’s easy to work with, but occasionally you’ll get errors which take forever to debug. Take a look at the following code and write down what you think the output will be. #include <iostream> class Base { public:     virtual void test(int x = 0)     { […]