Global variables and side effects

Sometimes people write programs in such a way that an assignment is made inside a function to a non-local variable. This is sometimes called a side-effect. This type of programming is strongly discouraged, but often happens in recursive functions, when short-cuts are taken. Here is an example derived from [1] of a function called sneaky().

#include <stdio.h>

int a, z;

int sneaky(int x)
   z = z - x;
   return x*x;

int main(void)
   z = 10;
   a = sneaky(z);
   printf("%d %d\n", a, z);
   z = 10;
   a = sneaky(10)*sneaky(z);
   printf("%d %d\n", a, z);
   z = 10;
   a = sneaky(z)*sneaky(10);
   printf("%d %d\n", a, z);

return 0;

Here is the output:

100 0
0 0
10000 -10

As you can see, how sneaky() is used clearly defines what the output will look like.

[1] Jensen, K., Wirth, N., Pascal User Manual and Report (2nd ed.), Springer-Verlag (1978).

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.