C&C++ goto statement

The codes of C&C++ programs get execute in sequence the first line followed by the second one and so on. To make a program more understandable, you can separate its codes; every action in it own part. Now, once you want you program to disrespect the first-come-first-serve rule, you may use the goto to tell your program which line is next.

As your program is dividedinto parts, you have to make every part recognised by using a name. Such name is what is called a label; itsmade of any user defined keyword followed by a colon (keyword:).

A C example

#include <stdio.h>

int main() {

top:

printf(“Hello World!”);

goto top;

}

A C++ example

#include <iostream>

int main() {

top:

std::cout<<“Hello World!”;

goto top;

}

Ok, now rewrite any of the above in Dev-C++. To save, go to file

and choose save_as > choose a location > type the

filename > add a .c suffix to C and .cpp for C++ (if your filename

was hello, it’s now hello.c or hello.cpp) > click save

To run you program, click execute and choose compile

and run.

If Dev-C++ fail, to run your program; it means you used the

copy and paste tactic. So, go to your codes to delete and

rewrite the double quotes.

Understanding these codes

#include <stdio.h>

As the name says it, Dev-C++ was designed for C++.

However, it can also work for C because C++ was developed in C. So, the above line tell Dev-C++ that we are creating a C program. If its C++ we use #include <iostream>. Stdio.h is short for Standard Input Output Header and iostreamis short for input output stream. We will learn more about headers next time.

int main() creates a function called main and two curry brackets { } are which hold the instructions for this function. The two parenthesis () are which indicate it is a

function. Once you try to run a program made in C or C++, it calls a function call main. A C or C++ program can’t run with no main function.

top: creates a label called top. Label are destinations that can be reached using the goto command.

printf is a built-in C function for displaying text on the screen. Contents between the two parenthesis () are passed to the function so that instructions in that function can access these contents.

std::cout is C++ command to display text on the screen. Std is short for standard and cout is short for console output. The two opening arrow brackets << indicate the string “Hello World!” is passed to the cout command.

The double quotes are used to hold strings in C&C++.

String is another name for text.

goto takes the execution to the part called top. Because of the statement goto top both of the above programs once run will keep displaying “Hello World!” instead of terminating. You can use a similar goto statement for the execution to jump to any point in your program codes.

 

© Mihigo ER Anaja

Write to me for more;

https://www.facebook.com/mihigoanaja

https://iblink.ning.com/members/mihigoeranaja