Home > Back-end >  Declaring int values before the main() function VS after C
Declaring int values before the main() function VS after C

Time:11-15

What is the difference between: `

#include <iostream>
using namespace std;
int n,d,nr;
int main()
{
    cin>>n;
    
    for(d=1; d*d<n; d  ){
        if(n%d==0){
            if(d%2==0) nr  ;
            if(n/d%2==0) nr  ;
        }
    }
    if(d*d==n&&d%2==0) nr  ;
    
    cout<<nr;
}

`

AND

`

#include <iostream>
using namespace std;

int main()
{
    
    int n,d,nr;
    cin>>n;
    
    for(d=1; d*d<n; d  ){
        if(n%d==0){
            if(d%2==0) nr  ;
            if(n/d%2==0) nr  ;
        }
    }
    if(d*d==n&&d%2==0) nr  ;
    
    cout<<nr;
}

` I input 12 and expect 4. The first one works the second one dosen't.

Declaring the n,d,nr integers before the main() returns a different value as against declaring them after the main() function. Why?

CodePudding user response:

Variables declared outside of a function or class have "file scope" lifetime. This basically means that they are global variables.

Integers with file scope are initialized as 0, and as a result int n,d,nr; are all initialized to 0 in the first example.

Of particular interest is nr, because it is otherwise unassigned to. This means that it has an indeterminate value when declared inside of main


(Edited to add standardese)

More formally, int n,d,nr; in the top example have namespace scope. That is, the smallest scope they are declared in is the global scope/global namespace. (Per [basic.scope] and [basic.namespace]).

Variables with namespace scope are defined to have static storage duration (per [basic.stc.static])

Variables with static storage duration are zero initialized at program start (per [basic.start.static]).

CodePudding user response:

The difference is when you define your variables before main(at global scope) they just get zeroed for you. But when you define your variables in a function without an initial value their value will vary.

Your problem is that nr variables is not initialized with zero value. just do nr=0;

  • Related