I made 2 projects, the first one in C and the second one in C++, both work with same behavior.
C project:
header.h
int varGlobal=7;
main.c
#include <stdio.h>
#include <stdlib.h>
#include "header.h"
void function(int i)
{
static int a=0;
a++;
int t=i;
i=varGlobal;
varGlobal=t;
printf("Call #%d:
i=%d
varGlobal=%d
",a,i,varGlobal,t);
}
int main() {
function(4);
function(6);
function(12);
return 0;
}
C++ project:
header.h
int varGlobal=7;
main.cpp
#include <iostream>
#include "header.h"
using namespace std;
void function(int i)
{
static int a=0;
int t=i;
a++;
i=varGlobal;
varGlobal=t;
cout<<"Call #"<<a<<":"<<endl<<"i="<<i<<endl<<"varGlobal="<<varGlobal<<endl<<endl;
}
int main() {
function(4);
function(6);
function(12);
return 0;
}
I read that global variables are extern by default and in C and static by default in C++; so why does the C++ code works?
I mean int varGlobal=7; is same as static int varGlobal=7; and if it's static then it can be used only in the file it was declared, right?
See Question&Answers more detail:os