When declaring pointers, are they only effective when declared in the block { } they are going to be used for only? Can't they also be global instead of local to a block { }?
For example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
#include <iostream>
usingnamespace std;
int num;
int *pt; // pointer of type int
pt = #
int main()
{
*pt = 10;
cout << num;
return 0;
}
Errors I get when compiling:
Error E2303: Type name expected
Error E2238: Multiple declaration for 'pt'
Error E2344: Earlier declaration of 'pt'
So unlike many other programming languages, we cannot assign/initialize values to variables outside of a function, but only possible to declare them instead?
Hmm if so, wasn't aware of that with C++. I guess because I was use to certain other languages were that is okay to do. The more I learn C++, the more I see it's differences and how it is definitely a "strict" language to learn/follow, but I'm really liking it! :)
That's because in other languages, such as Python or Lua, the source file is a program.
In C and C++, source files are more like instructions for the compiler to use to generate programs, rather than programs in themselves. In them, you say what data the program should contain, what functions it should contain, and what they do. Since the function is the fundamental unit of execution in procedural programming, only functions can contain code. Assignments in data definitions are exceptions because they translate to specific code in a special function created by the compiler. Being able to put code outside of functions in this context would be like telling the compiler, not the program, to do something.
Oh, one more thing: In the case of C++, it is in fact possible to have the compiler behave as an interpreter. Templates are Turing-complete, so they can be used, for example, to have the compiler compute a short list of prime numbers, or of Fibonacci numbers.