Global Variables klappt nicht



  • Hallo erstmal!

    Bin neu hier im Forum und bin gerade dabei C++ einigermaßen zu lernen.
    Lese derzeit ein Buch namens "C++ from the Ground Up ~ 3rd Edition" von Herbert Schildt.

    Und zwar habe ich folgendes Problem:

    #include <iostream>
    using namespace std;
    
    void func1();
    void func2();
    
    int count; // this is a global variable
    
    int main()
    {
    int i; // this is a local variable
    for(i=0; i<10; i++) {
    count = i * 2;
    func1();
    }
    return 0;
    }
    
    void func1()
    {
    cout << "count: " << count; // access global count
    cout << '\n'; // output a newline
    func2();
    }
    
    void func2()
    {
    int count; // this is a local variable
    for(count=0; count<3; count++) cout << '.';
    }
    

    Aus irgendeinem Grund kann ich nicht debuggen. In der Fehlermeldung steht das ich nirgendswo "count" deklariert habe. Aber das habe ich doch in Zeile sieben!

    Danke!
    Aydo 🙂 🙂



  • vermutlich liegt das daran, dass du die Variable count 2x dekleriert hast, 1x in Zeile 7 und in func 2.
    (auch wenn es bei mir trotzddem fehlerfrei compilert.)

    du könntest zB mal versuchen die in func2 einfach count2 zu nennen:

    #include <iostream> 
    using namespace std; 
    
    void func1(); 
    void func2(); 
    
    int count; // this is a global variable 
    
    int main() 
    { 
    int i; // this is a local variable 
    for(i=0; i<10; i++) { 
    count = i * 2; 
    func1(); 
    } 
    return 0; 
    } 
    
    void func1() 
    { 
    cout << "count: " << count; // access global count 
    cout << '\n'; // output a newline 
    func2(); 
    } 
    
    void func2() 
    { 
    int count2; // this is a local variable 
    for(count2=0; count2<3; count2++) cout << '.'; 
    }
    

    mfg,
    andi01.



  • C:\Users\... In function int main()': C:\\Users\\...count' undeclared (first use this function)
    (Each undeclared identifier is reported only once for each function it appears in.)
    C:\Users\... In function void func1()': C:\\Users\\...count' undeclared (first use this function)

    Ich benutze DEV-C++, könnte es vllt. daran liegen?



  • Aydo schrieb:

    Ich benutze DEV-C++, könnte es vllt. daran liegen?

    Könnte sein - ist auf jeden Fall ne veraltete IDE - gab in letzter Zeit (so gar hier im Forum) immer mal wieder wirklich gute Gründe, auf DEV-C++ zu verzichten^^
    alternativen: Visual Studio Express, Code::Blocks, netbeans, ...

    bb



  • vielleicht, dev c++ ist ein veralteter compiler der nicht mehr weiterentwickelt wird. Ich benutze Microsoft Visual C++ 2008 Express Edition, da geht der obige code fehlerfrei. der compiler zB ist neu und relativ bugfrei im vergleich zu dev.

    versuche aber erstmal den obigen korrigierten code, du hattest nämlich count 2x dekleriert. einfach mal mit diesem code probieren 🙂

    mfg,
    andi01.



  • andi01 schrieb:

    vielleicht, dev c++ ist ein veralteter compiler der nicht mehr weiterentwickelt wird.

    versuche aber erstmal den obigen korrigierten code, du hattest nämlich count 2x dekleriert. einfach mal mit diesem code probieren 🙂

    mfg,
    andi01.

    ne, der war scho korrekt - count wurde dann halt in der fkt von der lokal deklarierten variable überdeckt...
    sieht mir definitiv nach nem dev-c++ bug aus



  • jo, hab ich oben grade editiert^^

    dev is echt buggy...

    ich habe MS Visual C++ 2008 Express Edition, relativ bugfrei. der compiler wäre zB empfehlenswert 👍

    falls du bei dev c++ bleiben willst nimm meinen verbesserten code.

    mfg,
    andi01.



  • @ andi01
    Mit der Änderung klappt es leider immernoch nicht.
    Habe zwar Visual C++ 2008 aufm Rechner, benutzt habe ich es jedoch nicht weil ich beim Debuggen immer irgend einen Link eintragen musste und so.

    Danke mal das das an DEV-C++ liegt, weil es im Buch ja auch geht:

    Global Variables
    You may be wondering how to make a variable and its data stay in existence throughout
    the entire execution of your program. You can do this in C++ by using a global variable.
    Unlike local variables, global variables will hold their value throughout the lifetime of
    your program. You create global variables by declaring them outside of all functions.
    A global variable can be accessed by any function. That is, a global variable is available
    for use throughout your entire program.
    In the following program, you can see that the variable count has been declared
    outside of all functions. Its declaration is before the main( ) function. However, it
    could have been placed anywhere, as long as it was not in a function. Remember,
    though, that since you must declare a variable before you use it, it is best to declare
    global variables at the top of the program.

    #include <iostream>
    using namespace std;
    void func1();
    void func2();
    int count; // this is a global variable
    int main()
    {
    int i; // this is a local variable
    for(i=0; i<10; i++) {
    count = i * 2;
    func1();
    }
    return 0;
    }
    void func1()
    {
    cout << "count: " << count; // access global count
    cout << '\n'; // output a newline
    func2();
    }
    void func2()
    {
    int count; // this is a local variable
    for(count=0; count<3; count++) cout << '.';
    }
    

    Looking closely at this program, it should be clear that although neither main( ) nor
    func1( ) has declared the variable count, both may use it. In func2( ), however, a
    local variable called count is declared. When func2( ) uses count, it is referring to
    its local variable, not the global one. It is important to remember that if a global variable
    and a local variable have the same name, all references to that variable name inside
    the function in which the local variable is declared will refer to the local variable and
    not to the global variable.



  • Ziel der Übung sollte vermutlich nur sein folgendes zu verstehen:
    wird die variable außerhalb einer Funktion dekleriert ist sie global:

    int globale_variable;
    
    int main()
    {
    return 0;
    }
    

    lokale Variable:

    int main()
    {
    int lokale_variable;
    return 0;
    }
    

    Unterschied globale/lokale Variable:

    Die lokale Variable wird nachdem die Funktion, in der sie dekleriert wurde, beendet ist wieder gelöscht und ist auch in keiner anderen Funktion verfügbar, deklerierst du sie zB in main kannst du innerhalb von func1 nicht darauf zugreifen.
    Die globale variable ist, wie der Name schon sagt, global, d.h. in alle funktionen, verfügbar und wird erst nach Programmende gelöscht.

    hier mal ein Beispiel, anhand dessen man den Sinn einer globalen Variablen besser versteht und das auh funktioniert:

    #include<iostream>
    #include<conio.h>
    using namespace std;
    
    void func1();
    
    int globale_variable=1;
    
    int main()
    {
    cout<<"Wert der globalen Variablen: "<<globale_variable<<endl;/*hier wird 1 ausgegeben, das funktioniert, weil diese variable in allen funktionen verfügbar (global) ist*/
    
    int lokale_Variable=0;
    cout<<lokale_variable<<endl;/*das funktioniert, denn wir befinden uns hier innerhalb der Funktion, in der lokale_variable dekleriert wurde (main)*/
    
    func1();
    }
    
    void func1()
    {
    cout<<globale_variable;/* das funktioniert, da die Variable in allen Funktionen verfügbar ist, eben global*/
    
    /*
    folgendes würde eine Fehlermeldung produzieren:
    
    cout<<lokale_variable;
    
    denn:  lokale:variable wurde in main dekleriert, hier sind wir aber außerhab von main()!*/
    }
    

    mfg,
    andi01.



  • Danke Andi!

    Habs jetzt mal mit Visual C++ 2008 gestartet (also die .cpp Datei).

    WIll jetzt keinen neuen thread eröffnen, also frage ich mal hier:

    Wieso kann ich meine Datei nicht einfach debuggen? Oben kann ich nicht drauf drücken.



  • Aydo schrieb:

    @ andi01
    Mit der Änderung klappt es leider immernoch nicht.
    Habe zwar Visual C++ 2008 aufm Rechner, benutzt habe ich es jedoch nicht weil ich beim Debuggen immer irgend einen Link eintragen musste und so.

    Da machst du sicherlich was falsch^^
    Eigtl muss man nur nen Haltepkt setzen und dann gucken, was passiert ;o)





  • der compiler ist in der handhabung etwas komplizierter.

    das ganze geht so:

    1.neues projekt erstellen:
    -programm öffnen
    -datei->hinzufügen->neuesProjekt
    -namen und speicherort eingeben ->ok
    -weiter
    -vorkompilertes header auswählen
    -fertig stellen

    2.die richtige .cpp-datei öffnet sich
    [wenn nicht: wenn dein projekt zB test heißt, rechts im projektmappenexplorer doppelklich auf test.cpp machen]

    3.#include"stdfax.h" MUSS stehen bleiben!

    4.Code darunter einfügen

    5. zum debuggen F5 drücken oder auf den grünen pfeil in der Kopfleiste klicken

    was das mit deinem code betrifft: ich werde dn mal eben etwas umschreiben sodass er sicher funktioniert und dann posten^^

    mfg,
    andi01.



  • ne - einfach mal erstellen -> "empty project"
    dann hat man auch keinen pch an der backe, obwohl man ihn nicht braucht - spart wieder die klicks zum deaktivieren - und man braucht eben nicht wissen, wie man ihn deaktiviert

    bb



  • das geht auch^^

    zum code:
    so sollte er sicher funktionieren und auch verständlicher sein:

    #include<iostream>
    #include<conio.h>
    using namespace std;
    
    int count;
    
    void func();
    
    int main(
    {
    	for(int a=0;a<10;a++)
    	{
    		count=a*2;
    		func();
    	}
    	getch();
    }
    
    void func()
    {
    	cout<<"... count: "<<count<<endl;
    }
    

    dabei kommt auch das eigentliche ziel des Codes viel besser heraus:

    Eigentlich soll hier nur verstanden werden, dass die variable a aus der for-schleife sobald diese verlasen wird gelöscht wird und man auch nur innerhalb der schleife darauf zugreifen kann.
    Auf die globale Variable count kann jedoch auch in func() zugegriffen werden weil sie global ist.

    funktioniert mein code oben jetzt eigentlich auch bei dir unter dev c++?

    mfg,
    andi01.



  • ne...

    andi01 schrieb:

    #include "stdafx.h" //unnötig
    
    int _tmain(int argc, _TCHAR* argv[]) //argc/argv = unnötig, _tmain nicht standardkonform
    

    nur weil du nich empty project nehmen willst, nimmst du also lieber son dreck, der auf anderen compilern nicht kompilieren wird!? gj



  • empty project ist ja auch besser.

    dazu macht man fast alles wie oben, nur dass man eben nach dem projekterstellen folgendes tun muss:

    rechtsklick auf das projekt, hinzufügen->neue quelldatei, .cpp-datei auswählen, namen eingeben, ok, doppelklick drauf.

    edit: so, erledigt.

    @Aydo: funktioniert es jetzt?

    mfg,
    andi01.


Anmelden zum Antworten