I am making a program with functions and a global variable, the idea was to handle a global variable in several functions, I don't know how to make global functions, this is what I tried:
#include<cmath>
#include <stdio.h>
#include <iostream>
using namespace std;
int number=3;
void main(){
cout<<number;
}
void main(){
but I have no idea of the syntax mark on it because if it is supposed to number
be a global variable.
What is the problem?
Your understanding of global variables is correct.
Your mistake.
Your problem is not global variables. As other users have already pointed out, your function
main
is wrong; is incorrect because it should returnint
. The reason for this obligation is because (as the C++ language standard says ) otherwise your program will be incorrect, I show it to you directly extracted from the standard (translation and highlighting mine):So your syntax error is because your function
main
doesn't follow the standard. I bet even the compiler error is telling you that such a function should returnint
.Regarding the global variables.
Try not to use global variables :
I see two errors here: first, you use
void main(){
where it should beint main
, why? because you are going to return an integer. The second error I see is that you don't return it, that is, you don't add a return, as in the following code:I recommend you read this: input_output in c++ and local and global variables in c++ int-main-vs-void-main-in-c
The problem is that the function
main
is always of typeint
and must return a number.What do you want to achieve by using a global variable? Using global variables is not recommended and you may want to pass it by reference to your functions. For example:
Try this syntax , why? because it is a standard in C/C++, a
int main
and its respectivereturn 0
.