Concepts of Programming Languages

Today we are going to be looking at some basic syntax and semantics between the programming languages C, C++, and Java. I’ll run and rewrite the same code as well as explain the results.

Let’s start by creating a function that includes the following sequence of statements:

x = 21;
int x;
x = 42;

Programmed in C:

#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
function() {
x = 21;
int x;
x = 42;
printf("%d", x);
}
int main() {
function();
return 0;
}

A compiler error is thrown here, caused by the undefined identifier ‘x’. This is because a variable cannot be initialized before declaring it. We must first declare the variable ‘x’ as an integer, after which the variable can be used throughout the program.

Programmed in C++:

#include "stdafx.h"
#include <iostream>;
using namespace std;void function() {
x = 21;
int x;
x = 42;
}
int main() {
function();
return 0;
}

Here a compiler error is thrown as well, caused by the undeclared and undefined variable ‘x’. We must first declare the variable ‘x’ as an integer, after which the variable can be used through out the program.

Programmed in Java:

public class practice {     public static void main(String[] args){
practice fun = new practice();
fun.function();
}
public void function(){
x = 21;
int x;
x = 42;
System.out.println(x);
}
}

Again, a compiler error is thrown, caused by the undeclared and undefined variable ‘x’. We must again first declare the variable ‘x’ as an integer, after which we may use the variable through out the program.

The same compilation error is thrown in each of the languages C, C++, and Java. They all require declaration before initialization of a variable.

Now, we will specifically look at C++ and Java to determine whether the scope of a variable declared in a for loop is visible after the body of the statement.

Program in C++:

#include "stdafx.h"
#include <iostream>;
using namespace std;int main(){
for(int k = 0; k < 10; k++){
cout << k << endl;
}
cout << k;
return 0;
}

A compiler error is thrown, caused by the undefined identifier ‘k’. The variable ‘k’ is local to the for loop and cannot be referenced outside of the loop. Its scope is limited to the body of the for loop.

Program in Java:

public class practice{    public static void main(String[] args)
for(int k = 0; k < 10; k++){
System.out.print(k);
}
System.out.print(k);
}
}

A compiler error is thrown, caused again by the undefined identifier ‘k’. The variable ‘k’ is local to the for loop and cannot be referenced outside of the loop. The scope is again limited to the body of the loop.

The same compilation error is thrown in both languages C++ and Java. It does not recognize the variable ‘k’, because he compiler does not find a corresponding definition. The variable ’k’ is local to the body of the for loop and cannot be uninitialized outside of it.

Software Engineer