Simple Problems in C++ Part II

Better programmer is he who has better programming skills, for programming
skills one needs to PROGRAM because only reading won’t get you anywhere.
From regular programming comes good programming skill.


Solving problems basically means to write a program which performs the actions
as per the question. But the problems listed here are different; these problems
will check your understanding of the C++ programming language. You don’t
need to write any program.


In this article I have listed some of the good problems that I have come across,
which are related to what we discussed so far (variables, data types etc.).


This article is basically for beginners but even if you are an experience C++
programmer, you might want to look at them.


Problem No. 1


   //C++ Program
#include<iostream.h>
void main(void)
{
int arr[5]={2,3};
cout<<arr[2]<<arr[3]<<arr[4];
}

QUESTION: What will be the output of this program?


Problem No.2


   //C++ Program
#include<iostream.h>
void main(void)
{
int x=10,y=20,z=5,i;
i=x<y<z;
cout<<i;
}

QUESTION: What will be the output of this program?


Problem No.3


   //C++ Program
#include<iostream.h>
int i=10;
void main(void)
{
int i=20;
cout<<i;
}

QUESTION: What will be the output of this program?


Problem No.4


   //C++ Program
#include<iostream.h>
void main(void)
{
int i=10;
{
int i=20;
cout<<i;
}
}


QUESTION: What will be the output of this program?


Problem No.5


   //C++ Program
#include<iostream.h>
void main(void)
{
union un
{
short int i;
char ch[2];
};

union un u;

   u.ch[0]=3;
u.ch[1]=2;

   cout<<u.i;
}

QUESTION: What will be the output of this program?


Answers:


1. 000, when an array is partially initialized, the remaining elements are
automatically filled with 0s.


2. 1, look at the statement i=x<y<z;, here first x<y is evaluated
whose results is TRUE (or 1) then 1<z is evaluated which is again TRUE(or
1), therefore the value 1 is put into the variable x.


3. 20, since the variable which is local is given the priority.


4. 20, the variable which is more local is given the priority.


5. 515, HINT: short int is two bytes long and the character array (two
bytes as a whole) shares it.



Related Articles:


5 Common C++ Programming Mistakes

To err is human



It is normal for programmers to make mistakes while learning c++ programming.
Mistakes (or errors) are often caused by misconception in the programmers mind
or by forgetting certain things.

While syntax errors are easier to spot since the c++ compiler shows the related
information but logical errors often remains unnoticed, and many a times the
program works just as fine.

It is not possible to completely eliminate errors by yourself but it is definitely
possible to minimize them as a c++ programmer.

Here I am listing 5 of the common mistakes (errors) that beginners commit (not
sorted in any order).


Mistake No. 1


Have a look at this C++ Program


   #include<iostream.h>
void main(void)
{
int base,height,area;
cout<<"Enter the base and height of the triangle:";
cin>>base>>height;
area=0.5*base*height;
cout<<endl<<"AREA:"<<area;
}

Here the variable area is such that sometimes its value would be whole number
and sometimes it would be fractional. As long as we are giving even data the
program would output correctly, but giving odd data would result in the loss
of data in the output, since the integer data type can’t hold fractional
values.


Mistake No.2


  #include<iostream.h>
void main(void)
{
char name[15]=’c++ program’;
cout<<name;
}

Here the problem is in the line

char name[15]=’c++ program’;

since we are giving string data as character constant.

It should have been like this

char name[15]=”c++ program”;


Mistake No. 3


   #include<iostream.h>
void main(void)
{
int a=10,b=20,c;
a+b=c;
cout<<c;
}


Can you spot the error, yes it is with the line

a+b=c;

here mathematical operations are being done in the left hand side and it is
being assigned the value of the variable c, which is not possible.

It should have been

c=a+b;


Mistake No.4


   #include<iostream.h>
void main(void)
{
int Name;
cin>>name;
cout<<"The value of Namee is:"<<name;
}

I have seen many peoples committing this mistake, remember that C++ is Case-Sensitive,
what it means is Name and name are two different identifiers for C++.


Mistake No. 5


   #include<iostream.h>
void main(void)
{
int arr[3];
cout<<"Enter three numbers:";
cin>>arr[1]>>arr[2]>>arr[3];

   cout<<"The numbers are:"<<endl;
cout<<arr[1]<<arr[23]<<arr[3];
}

This is also one of the most common mistakes that c++ programmers commit.

As I have previously discussed in the other articles that declaring an array
as

int arr[3];

means that it is for storing 3 elements of data type integer.

And while accessing or modifying the index number starts with 0 and ends with
one less than the total number of elements it can store.




Hope this article helps…

Modules and Run/Liberty BASIC

People have been asking for a way to create code libraries in Liberty BASIC for some time. I have thinking about how to do this using an in-memory model. Over the weekend Scott and I worked on adding some modularity to the Run/Liberty BASIC language. Here's how it works so far. We are open to suggestions.

The RUN statement has a new form. If I want to use mymodule.bas as a module in a program I am writing I would code it like this:

run "mymodule.bas", #myModule

This causes mymodule.bas to be compiled into memory. It will execute code up to the first wait statement. This is how values will be initialized. The program then becomes an object assigned to the #myModule handle.

Then you can call any function on that program from within the calling program, like so:

#myModule myFunction(myParameter)

or even use the invokation in a more complex expression:

print "digits: "; len(#myModule myFunction(myParameter))

You may recognize this syntax as being the same as for controlling widgets. It relies on the same underlying mechanisms to do its work.

When we're done with this, modular programs loaded this way will be cached in memory and will only recompile when the source file changes.

Simple Problem in C++

Interchanging the values of two variables…


What’s the big deal. You take one extra variable; put the first variable’s
value in it, copy the value of the second variable to the first one and then
copy the value of the extra variable to the first one and there you are!

But what, if I say that you don’t have to use the third variable, let’s
say because the memory is full and you are left with memory only sufficient
for storing two variables. Doesn’t make sense. Huh!

It makes sense if you want to gain programming skills because solving problems
is the only way to do it. In this article we start with a simple one.


So, how do we do it?


It is not very big deal to interchange the values of two variables without using
the third variable yet I have come across peoples who don’t think it can
be done.

To solve this problem we need to do two things (i)First we need to write down
the method (algorithm) of doing it (ii0 Secondly, we need to write the c++ code
from the algorithm.


The Method


The method of solving this problem is discussed in a step-by-step manner to
make it easily understandable.


SETP 1: Let us assume that we have two variables. First variable
is named var1 and second var2.


STEP 2: WE put different values int the variables. Suppose
we put the following values.

var1=15

var2=5


STEP 3: We have to do the following addition and subtraction

var1=var1-var2

(Now var1=10)


var2=var1+var2

(Now var2=15)


var1=var2-var1

(Now var1=5)


STEP 4: Wow! The values of the variable have been interchanged.
Initially the values were var1=15; var2=5

And now they are var1=5; var2=15

Now we proceed to the second part…


Program it


All said and done; now we only need to program it.



//Program to interchange the values of
//two variables without using the third one
#include<iostream.h>
void main(void)
{
int var1,var2;
cout<<"Enter two numbers:";
cin>>var1>>var2;

   //intercahnge is done here
var1=var1-var2;
var2=var1+var2;
var1=var2-var1;

   cout<<endl<<"After interchange values are:";
cout<<endl<<var1<<endl<<var2<<endl;
}

Simple isn’t it, how about trying this with three variables, for instance
if the initial values three variables are a=5; b=15; c=25 then after interchange
the values should be a=15; b=25; c=5.

Go ahead its easy!


Related Articles:


Half an Hour to Variables

I wrote this article yesterday when I was getting bored and was feeling too
lazy, all thanks to the hot weather here. I planned of meeting my friends but
at last I insisted on staying at home when I wrote this. Regarding the title,
I thought that if it took me an hour to write it then you would have to hardly
give Half an Hour to Variables.

Now coming to the serious stuff…


What is Variable


During program run we need to manipulate data and the data to be manipulated
are stored in memory locations known as variable. In the system memory, data
are stored in memory locations such as 0x00243 which are not easy to remember
if we have quite a lot of them. Variables are memory locations having a name
so that different memory locations can be distinguished easily.


Declaration and Initialization of Variables


The declaration of variable generally takes the following form:

type varname;

Here type is any valid data type and varname is the variable name.

Ex.

int age;

float temp;

Static initialization: Initialization means giving initial
value to a variable.

Ex. int var=100;

Here 100 is the static number with which the variable is initialized (given
initial value). This is type of initialization is known as static initialization
because the initial value given to the variable is known at the time of programming.

Dynamic initialization: Have a look at the following line
of code:

float avg=sum/count;

H ere avg is initialized with a value that is not known at the time of programming
and it may have different values during different program runs.(since sum and
count on which the value of avg depends, may have different values under different
circumstances)

Access Modifiers


Access modifiers change the way we access or modify a particular variable.

The two types of access modifiers are discussed below:

const: By declaring any variable as const, we are telling
the C++ compiler that the value of the variable will remain unchanged during
program run. If we try to modify a variable declared as const, the compiler
will report an error and the program won’t compile.

   //program to illustrate const Access Modifier
//this program would RUN
#include<iostream.h>
void main(void)
{
const float pi=3.14;//declration and initialization of variable as const

int rad;
float area;
cout<<"Enter radius of circle:";
cin>>rad;
area=(rad*rad)*pi;//here the variable is only being accessed an NOT modified

cout<<endl<<"Area of the circle:"<<area;

}

Let us have a look at another program:


   //program to illustrate const Access Modifier
//this program would NOT RUN
#include<iostream.h>
void main(void)
{
const float pi;//declaration of variable as const
pi=3.14;//variable is being modified, NOT ALLOWED
int rad;
float area;
cout<<"Enter radius of circle:";
cin>>rad;
area=(rad*rad)*pi;//here the variable is only being accessed an NOT modified

cout<<endl<<"Area of the circle:"<<area;

}

volatile: By declaring any variable as volatile, we are telling
the compiler that the value of the variable can change by ways other than explicitly
defined by the program. In other words the value of the variable can be changed
by programs or routines outside the program (say, by the Operating System).

For example we can pass the variable declared as volatile to the operating system
clock routine to automatically keep track of the time changes.

It is necessary to declare those types of variables whose value can change outside
the program as volatile. C++ treats variables in such a way that if we don’t
and since the program is not modifying the variable’s value, the program
may output unexpected results.


Related Articles:


C++ Data Types in Detail

Data types are means to identify the type of data and associated operations
of handling it. C++ provides a predefined set of data types for handling the
data it uses. When variables are declared of a particular data type then the
variable becomes the place where the data is stored and data types is the type
of value(data) stored by that variable.

Data can be of may types such as character, integer, real etc. since the data
to be dealt with are of may types, a programming language must provide different
data types.

In C++ data types are of two types:-



  1. Fundamental Data Types: As the name suggests these are
    the atomic or the fundamental data types in C++. Earlier there was five of
    these (int, char, float, double and void) but later two new data types namely
    bool and wchar_t have been added. Int stores integer data or whole numbers
    such as 10, -340 etc., char stores any of the ASCII characters, float is used
    to store numbers having fractional part such as 10.097, double stores the
    same data as float but with higher range and precision, bool can only store
    true and false values.
        //Program to illustrate various fundamental data type
    #include<iostream.h>
    void main(void)
    {
    int age;
    float salary;
    char code;
    cout<<"Enter age, salary and code:";
    cin>>age;
    cin>>salary;
    cin>>code;
    cout<<endl;//goto next line
    cout<<"DETAILS"<<endl;//short for cout<<"DETAILS";cout<<endl;

    cout<<"Age:"<<age<<endl;
    cout<<"Salary:"<<salary<<endl; cout<<"Code:"<<code<<endl;



    }



  1. Derived Data Types: These are the data types which are
    derived from the fundamental data types. It is further divide into two categories
    i)Built-In and ii)User-defined, which are discussed below as seperate topics.

Built-In Derived Data Type

  1. Arrays: Arrays refer to a list of finite number of same
    data types. The data in the array can be accessed by an index number ranging
    from 0 to n(where n is the number of data element it can store). Ex- if arr[3]
    is an array of int(egers) then the different values in the array can be accessed
    as shown below.

    arr[0], arr[1],arr[2]

    when we declare an array such as the one sown above then by arr[3] we mean
    that we want three elements in the array and hence while accessing arr[2]
    is the last element.


        //Program to illustrate arrays
    #include<iostream.h>
    void main(void)
    {
    int arr[3];//it will store 3 integer elements
    cout<<"enter 3 numbers:";
    cin>>arr[0]>>arr[1]>>arr[2];//this statement is same as using three cin's

    cout<<endl;//goto next line
    cout<<arr[0]<<arr[1]<<arr[2];

    }


  2. Pointer: A pointer is a variable that holds the memory
    address of other variable. It is also of different data types, ex- char pointer
    can store address of only char variables, int pointer can store address of
    int variables and so on.
  3. Reference: A reference in the simplest sense is an alias
    or alternate name for a previously defined variable.

         
    //Program to illustrate References
    #include<iostream.h>
    void main(void)
    {
    int var;
    int &refvar=var;//here a reference variable to var is declared remember var was previously declared

    var=10;//var is given the value 10
    cout<<var<<endl;
    refvar=100;//reference variable of var is changed

    cout<<var;//but var also gets changed

    }


User-Defined Derived Data Types


  1. Class: A class is a collection of variables and function
    under one reference name. it is the way of separating and storing similar
    data together. Member functions are often the means of accessing, modifying
    and operating the data members (i.e. variables). It is one of the most important
    features of C++ since OOP is usually implemented through the use of classes.

  2. Structure: In C++ structure and class same except for
    some very minor differences.

  3. Union: A union is a memory location shared by two or more
    different variables, generally of different data types. Giving more details
    here would only confuse you; I’ll leave it for future articles.

  4. Enumerations: It can be used to assign names to integer
    constants.

         //Program to illustrate Enumerators
#include<iostream.h>
void main(void)
{
enum type{POOR,GOOD,EXCELLENT};//this is the syntax of enumerator

int var;
var=POOR;//this makes programs more understandable
cout<<var<<endl;
var=GOOD;
cout<<var<<endl;
var=EXCELLENT;
cout<<var;

}

Data Types Modifiers


  • signed

  • unsigned

  • short

  • long




Int, char, float, double data types can be preceded with these modifiers to
alter the meaning of the base type to fit various situations properly.

Every data type has a limit of the larges and smallest value that it can store
known as the range. An integer (usually 4 bytes long) can store any value ranging
from -2147483648 to 2147483647. Data Type modifiers usually alter the upper
and lower limit of a data type.

Unsigned modifier makes a variable only to store positive values. Ex- if a data
type has a range from –a to a then unsigned variable of that type has
a range from 0 to 2a. Preceding any data type with signed is optional because
every data type is signed by default. Short integers are 2 bytes long and long
integers are 8 bytes long.


Related Articles:


Privacy Policy

Privacy Policy for Learning Computer Programming


The privacy of our visitors to Learning Computer Programming is important to us.


At Learning Computer Programming, we recognize that privacy of your personal information is important. Here is information on what types of personal information we receive and collect when you use and visit Learning Computer Programming, and how we safeguard your information.  We never sell your personal information to third parties.


Log Files

As with most other websites, we collect and use the data contained in log files.  The information in the log files include  your IP (internet protocol) address, your ISP (internet service provider, such as AOL or Shaw Cable), the browser you used to visit our site (such as Internet Explorer or Firefox), the time you visited our site and which pages you visited throughout our site.


Cookies and Web Beacons

We do use cookies to store information, such as your personal preferences when you visit our site.  This could include only showing you a popup once in your visit, or the ability to login to some of our features, such as forums.


We also use third party advertisements on Learning Computer Programming to support our site.  Some of these advertisers may use technology such as cookies and web beacons when they advertise on our site, which will also send these advertisers (such as Google through the Google AdSense program) information including your IP address, your ISP , the browser you used to visit our site, and in some cases, whether you have Flash installed.  This is generally used for geotargeting purposes (showing New York real estate ads to someone in New York, for example) or showing certain ads based on specific sites visited (such as showing cooking ads to someone who frequents cooking sites).


DoubleClick DART cookies

We also may use DART cookies for ad serving through Google’s DoubleClick, which places a cookie on your computer when you are browsing the web and visit a site using DoubleClick advertising (including some Google AdSense advertisements).  This cookie is used to serve ads specific to you and your interests (”interest based targeting”).  The ads served will be targeted based on your previous browsing history (For example, if you have been viewing sites about visiting Las Vegas, you may see Las Vegas hotel advertisements when viewing a non-related site, such as on a site about hockey).  DART uses “non personally identifiable information”.  It does NOT track personal information about you, such as your name, email address, physical address, telephone number, social security numbers, bank account numbers or credit card numbers.  You can opt-out of this ad serving on all sites using this advertising by visiting http://www.doubleclick.com/privacy/dart_adserving.aspx  


You can choose to disable or selectively turn off our cookies or third-party cookies in your browser settings, or by managing preferences in programs such as Norton Internet Security.  However, this can affect how you are able to interact with our site as well as other websites.  This could include the inability to login to services or programs, such as logging into forums or accounts.


Deleting cookies does not mean you are permanently opted out of any advertising program.  Unless you have settings that disallow cookies, the next time you visit a site running the advertisements, a new cookie will be added.

Introduction to C++ Programming



This article gives you an introduction to C++ Programming from ground level.
This article won't teach you all the fundas of C++ programming rather it gives
you the base to learn C++ programming, remember that for further learning, the
base should be strong and this is what this article tries to do. It would let
you know many fundas which will help you in further learning of the the language.
C++ was developed in 1980s in the Bell Laboratories by Bjarne Stroustrup as
an object oriented programming language. This language is considered by many
as an extension of the programming language C. The extension of programming
language C to create C++ is obtained by adding classes to C. This is why C++
was initially called “C with Classes”. The C++ programming language
derives its name from the increment operator used in C, which increments the
value of a variable. The symbolic name of C++ rightly indicates that this language
is enhanced version of C.


Features of C++ Programming Language:-



  • C++ programming language is highly flexible, versatile and very powerful
    programming language for developing any software specially the system software
    namely operating system, compilers etc.


  • C++ is most ideally suited language for development of reusable programs,
    which is very important to keep the production cost minimum.

    Comparison of C++ Programming Language


Let us see how C++ compares with other programming languages. All the
programming languages can be divided into two categories:-



  • Problem oriented languages or High-level languages: These languages have
    been designed to give a better programming efficiency, i.e. faster program
    development. Examples of languages falling in this category are FORTRAN, BASIC
    etc.


  • Machine oriented languages or Low-level programming languages. These languages
    have been designed to give a better machine efficiency, i.e. faster program
    execution. Examples of programming languages falling in this category are
    Assembly Language and Machine Language.



C++ stands in between these two categories. That’s why it is often called
a Middle level language, since it was designed to have both: a relatively good
programming efficiency (as compared to Machine oriented languages) and relatively
good machine efficiency (as compared to Problem oriented languages).


Getting Started with C++ Programming


Communicating with a computer involves speaking the language the computer understands,
which immediately rules out English as the language of communication with computer.
However, there is a close analogy between learning English language and learning
C++ language. The classical method of learning English is to first learn the
alphabets or characters used in the language, then learn to combine these alphabets
to form sentences and sentences are combined to form paragraphs. Learning C++
programming is similar and much easier.Therefore, instead of straight-away learning
how to write programs, we must first know what alphabets, numbers and special
symbols are used in C++, then how using these, constants, variables and keywords
are constructed, and finally how are all these combined to form an instruction.
A group of instruction would be combined later on to form a program.


Character Set: Character set is a set of valid characters
that the language can recognize. Acharacter represents any letter, digit or
any other sign. C++ has the following character set:-



  • Letters A-Z, a-z


  • Digits 0-9


  • Special Symbols space + - * / ‘ “ ( )[ ] etc.White Spaces blank
    space, horizontal tab, carriage return, newline etc.


Other Characters, C++ can process any of the 256 ASCII characters as data or
as literals.The alphabets, numbers and special symbols when properly combined
form constants, variables and keywords. Let us see what these are:-


Constants: Constants are data items that never change their
value during a program run. C++ programming language allows several kinds of
constants.


Variables: Variables are quantities that may vary during program
execution. Variable names are names given to locations in the memory of computer
where the value is stored.


Keywords: These are the words that convey a special meaning
to the language compiler. Keywords are the words whose meaning has already been
explained to the C++ compiler. The keywords cannot be used as variable names
because if we do so we are trying to assign a new meaning to the keyword, which
is not allowed by the computer. Examples of keywords are if, void, for, switch
etc.


Data Types in C++


Data types are means to identify the types of data and the associated operations
to handle it. In C++ data types are broadly of two types:-



  • Fundamental Data Types: These are predefined to the C++
    language itself. there are at least five fundamental data types. char- represents
    that the declared variable of this type can store characters int- represents
    integers float- represents floating point numbers void- represents valueless
    data


  • Derived Data Types: These are constructed from the fundamental
    types. I will not give you the details here because this is a bit high-level.



Instructions in C++ Programming Language


Now that we seen the different types of constants, variables and keywords the
next logical step is to learn how they are combined to form instructions.



  • Type declaration instructions: to declare the type of variables
    used in the program. Eg:- int num; Here a variable num is declared of type
    int(eger).


  • Input /Output instructions: to perform the function supplying
    input data to a program and obtaining the output results from it. Eg:- cin>>a;
    cout<<”Hello”; In the first line input is taken from the
    keyboard by the function cin and is assigned to a pre-declared variable a.
    In the second line ‘Hello’ is printed using the function cout.



  • Arithmetic instructions: to perform arithmetic operation
    between constants and variables. Eg:- c=a+b; Here c is assigned a value which
    is the sum of the variables a and b.


  • Control instructions: to control the sequence of execution
    of various statements in a C++ program. Eg:- if (a>b) func1(); Here it
    is checked whether a is greater than b, if it is, then program execution goes
    to a user defined function ‘func1’.



The first C++ Program


Armed with the knowledge about the types of variables, constants, keywords
etc. we would write down our first C++ program.Each instruction in a C++ program
would comprise of a series of statements. These statements must appear in the
same order in which we want them to be executed. The following rules are applicable
to all C++ programs no matter ho long or complicated they are.



  • Blank spaces may be inserted between two words to increase readability of
    the statements. However, no blank spaces are allowed within a variable, constant
    or keyword.


  • Usually all statements are entered in small case letters.


  • C++ has no specific rules for the position at which a statement is to be
    written. That’s why it is often called free-form language.


  • Any C++ statement always ends with a semicolon (;). Now, let us have a look
    at a program which calculates the sum of two numbers given by the user.



Now, let us have a look at a program which calculates the sum of two numbers
given by the user.






//To calculate the sum of two given numbers
#include<iostream.h>

main()
{

int num1; //declares a variable num1 of type int(etger)

int num2; //declares a variable num2 of type int(etger) 

int total; //declares a variable sum of type int(etger) 

cin>>num1; //takes input and stores to the var num1 

cin>>num2; //takes input and stores to the var num2 

total= num1+num2; //adds vars num1 & num2 

cout<<total; //prints the value of the variable

}


A few useful tips:-



  • Any C++ program is nothing but a combination of functions, main() is one
    such function which is always there in a C++ program in one form or the other.
    Empty parentheses are necessary after main.


  • The set of statements belonging to a function is enclosed within a pair
    of braces Ex. main() { statement1; statement2; statement3; statement4; }


  • Any variable is declared before using it.


  • Any C++ statement should always end with a semicolon.

    iostream.h is the file needed to use the functions cin and cout, which is
    included in the program with the include keyword.



Summary


After going through the article you have got an introduction to C++ Programming,
you now know what C++ is and how it is used. You now know the C++ language and
have learnt some of the most fundamental parts of C++. you have learnt how to
declare variables and how to use them in arithmetic operations. In one sentence
you have got an introduction to C++ programming which will help you in further
learning of the language

Inkey$ and Liberty BASIC

There has been some discussion in the support forum about extending keyboard handling in Liberty BASIC programs. Currently we only allow doing something like this in the graphics views. Two things (maybe more?) are missing:
  • Getting the next character in the mainwindow without stopping the program. Currently only INPUT and INPUT$() are supported. Both stop the program and wait.
  • Getting the next character typed for some window or widget that has focus. In other words, reading keypresses for objects with handles (ie. #thisWindow)

What I suggested in the forum is a function called inkey$().

The following would read keypresses for the mainwindow:

print inkey$()

or it could be abbreviated to:

print inkey$

To read keypresses for windows or widgets with handles:

print inkey$(#handle)

I'd like to solicit feedback here. Any ideas? Please leave a comment, and thanks!

BASIC and CSS

One of the important aspects of integrating a programming language with web development is page layout. Until recently this would have meant inserting lots of HTML tags into your source code. You can do this with Run BASIC.

However there is a better way. It is called CSS (Cascading Style Sheets). This provides a way to wrap the things on your web page with tags that you give your own names to, and you defined the appearance of the stuff wrapped in those tags somewhere else. This way your program's code has very little extra stuff in it to clutter up your code. If there is too much clutter it can be very hard to understand what code means, and this can slow you down and lead to bugs.

So, Scott McLaughlin and I have begun to integrate CSS with Run BASIC. We added a CSSID statement (originally this blog entry had this as CSS, but we changed the command), a DIV statement, and an END DIV statement. Here's a very short example:

cssid #myTag, "{ background: #FFDDDD; font-family: tahoma }"

div myTag
print "count to ten"
for x = 1 to 10
print x
next x
end div

Okay, so this displays all the text printed between the DIV and the END DIV with a light red background, and using the tahoma font. The #myFont token isn't a handle like the ones used for files and GUI controls. The # is simply part of CSS syntax.

DIV statements can be nested, and the contents of one DIV block will be rendered on the page nested inside of each other.

There is a lot more that can be done with CSS, and we're trying to explore what are the simplest and most useful things to include in Run BASIC.

We will be posting a screencast in the next few days that shows how this works.

Custom deleters with smart pointers

There is just one smart pointer as part of the standard C++ library as of now (excluding the tr1 and proposals). That is the std::auto_ptr.

It is crucial to know that you can only use it for allocations made via the new operator. It neither handles, the allocations made via the array form of new or malloc or any other allocation routine provided, for that matter.

How can you extend it to be able to use it with those? Basically, you can't. There are an option though - you lay down your own version of auto_ptrs specific to those which have the delete call replaced by free/delete[]/or the relevant deleter. This will ask for writing down multiple classes for them and using them as appropriate. There is another way to extend it but before that let's look at how boost::shared_ptr handles it.

Boost shared_ptr has a concept for a custom deleter. The deleter would operate on the pointer (when the reference count drops to 0 - remembers the ownership is shared!) and the effect should be that of freeing the resource. The following is an illustration:

[CODE]

template<typename T>
struct mallocDeleter
{
    void operator() (T*& ptr)
    {
        if (ptr)
        {
            free(ptr);
            ptr=NULL;
        }
    }
};
void somefunction()
{
    MyType* ptr = getAllocatedPointer();//returns pointer to memory allocated by malloc
    shared_ptr<MyType, mallocDeleter<MyType> >object(ptr, mallocDeleter());
}

//scope ends shared_ptr's destructor gets called that then called mallocDeleter(ptr) - The default deleter is "delete".

Notice, how this expresses the flexibility. You could have acquired any other resource and would have wrapped it inside a shared_ptr and would provide the deleter to free that resource. For example, a File Handle - on which the custom deleter calls close (for C++ fstream objects, you don't need that - they already exploit RAII). Or, a db connection handle, for which the deleter would handle closing it. Just about anything that is manually allocated! Amazing how the ability to provide the deleter makes this smartness so generic.

I wonder why the auto_ptr or the boost scoped_ptr don't provide this ability. RAII is truely magic and takes care of resource leak issues so well.

Cheers!

Demo of Run BASIC at Smalltalk Solutions

Wednesday evening I had the priviledge of organizing the Seaside BOF (birds of a feather) session at Smalltalk Solutions. This meant that I was the one up at the microphone (which I pushed aside since the room wasn't big) for most of an hour and a half. It was fun and I didn't feel put on the spot since this was more of a round table than anything. I only had to try and direct the conversation some.

Here is James Robertson's blog entry with a photo of me presenting.

http://www.cincomsmalltalk.com/blog/blogView?entry=3355631481

I'm very small in the frame, but yeah that's me all right. You can make out the Run BASIC web page up on the screen if you look carefully.

The demo was a little bit scary since I was modifying the Run BASIC code almost right up to the last second before the meeting. Scott and I were spending most of our free time at the conference working on some simple CSS integration. I'm hoping to put a screencast up to show how it all works.

Check out this stream