Global vs Local var scope

I have two very simple questions in a global/local variable lesson.

In this lesson:
http://xoax.net/cpp/crs/console/lessons/Lesson11/

Giving Code:
1
2
3
4
5
6
7
8
#include <iostream>

int iX = 3;
void main()
{
    int iX = 5;
    std::cout << ::iX << std::endl;
}


Errors produced:
5 error: `main' must return `int'|
5 error: return type for `main' changed to `int'|
In function `int main(...)':|
6 warning: unused variable 'iX'|
||=== Build finished: 2 errors, 1 warnings (0 minutes, 1 seconds) ===|

My questions:
1. The void error disappears if I change Void to int. Why?
2. The nested iX value does not change to 5, displays 3. Why?

Nearly every example given in these lessons must have the void removed (changed to int) to compile.

Any suggestions appreciated.
Last edited on
1. The void error disappears if I change Void to int. Why?


Because, as already noted by the compiler error, the return type of main is required to be int.

2. The nested iX value does not change to 5, displays 3. Why?


Also, as already noted by the compiler warning, the nested iX value is never accessed. ::iX returns to the iX at global scope.

Reading the compiler messages might actually answer some of your questions.

[edit: If you're following tutorials that use void main it's probably a pretty good sign that they aren't quality tutorials.]
Last edited on
So how is the author of these tutorials getting his code to run with the voids in place the nested int declare in place?

Could you explain why the compiler gives a warning: Unused variable 'iX'?
iX is declared and set = 3, is this unused?

Because of the nested int declaration?

in the block, I removed the 'int' leaving iX = 5.

The code then runs yielding a 5, as expected (no warnings)

1
2
3
4
5
6
7
8
#include <iostream>

int iX = 3;
int main()
{
    iX = 5;
    std::cout << ::iX << std::endl;
}
Last edited on
So how is the author of these tutorials getting his code to run with the voids in place the nested int declare in place?

Most compilers have extensions to allow a void return type for main, and of those compilers many also have those extensions enabled by default.


Could you explain why the compiler gives a warning: Unused variable 'iX'?
iX is declared and set = 3, is this unused?

The global iX was used in the cout statement. It is the iX defined in the main function that is unused. It is almost always a mistake for a variable to be unused other than definition/intialization, so the compiler emits a (helpful) warning to that effect. Warnings don't stop compilation from succeeding. They're just information that is supplied to the user of the compiler.


He is using Code:: Blocks too i think. Just curious.

Code::Blocks is not a compiler. It is an IDE which can be used to interface with any of several compilers.
Topic archived. No new replies allowed.