Anonymous user
Scope/Function names and labels: Difference between revisions
→{{header|C}}: Fixed the worst of the C errors. This is not the competition page for the ugliest code.
m (→{{header|REXX}}: added/changed comments and whitespace, changed indentations.) |
(→{{header|C}}: Fixed the worst of the C errors. This is not the competition page for the ugliest code.) |
||
Line 88:
Demonstrating function scope as well as goto in a C program invariably leads to code like the one below. The [http://en.wikipedia.org/wiki/Scope_(computer_science)#C Wikipedia article] is a good starting point.
<lang C>/* Abhishek Ghosh, 8th November 2013, Rotterdam */▼
<lang C>▼
#include <stdio.h>▼
▲/*Abhishek Ghosh, 8th November 2013, Rotterdam*/
▲#include<stdio.h>
#define sqr(x) ((x) * (x))
#define greet printf("
int twice(int x)
{
return 2 * x;
}
int main(void)
{
int x;
printf("
printf("
printf("
if (scanf("%d", &x)
switch (x % 2) {
default:
case 0: printf("\nYou entered an even number.");▼
case 0:
printf("\nIt's square is %d, which was computed by a macro. It has global scope within the program file.",sqr(x));▼
break;▼
▲
case 1:
jumpin: printf("\n2 times %d is %d, which was computed by a function defined in this file. It has global scope within the program file.",x,twice(x));▼
goto sayhello
jumpin:
if(x==-1)goto scram; ▼
▲
break;▼
printf("Since you jumped in, you will now be greeted, again!\n");
sayhello:
greet;
printf("\nWe now come to goto, it's extremely powerful but it's also prone to misuse. It's use is discouraged and it wasn't even adopted by Java and later languages.");▼
if(x!=-1){▼
x = -1; /*To break goto infinite loop.*/▼
}
▲
scram: printf("\nIf you are trying to figure out what happened, you now understand goto.");▼
▲ return 0;
}
scram:
return 0;
{{out}} Example run:
<pre>
This will demonstrate function and label scopes.
All output is happening throung printf(), a function declared in the header
Enter a number
You entered an odd number.
Hello There
We now come to goto, it's extremely powerful but it's also prone to misuse.
2 times -1 is -2, which was computed by a function defined in this file. It has global scope within the
Since you jumped in, you will now be greeted, again
Hello There
If you are trying to figure out what happened, you now understand goto.
</pre>
|