0

I am a little bit confused about this two notions. I am reading the "C++ Programming Language", Bjarne Stroustrup. According to this book, the following are declarations and definitions :

char ch; //(dec. and def.)
string s; //(dec. and def.)
int count=1; //(dec. and def.)

But there is an exercise (4.11) that says " For each declaration in §4.9, do the following: If the declaration is not a definition, write a definition for it. If the declaration is a definition, write a declaration for it that is not also a definition."

So I am confused how can we write the declaration without the definition for the above three things ??

  • 1
    This probably will get more response with a language tag. I suspect it might be a duplicate though. – doctorlove Feb 12 '18 at 10:26
  • 2
    Possible duplicate of [What is the difference between a definition and a declaration?](https://stackoverflow.com/questions/1410563/what-is-the-difference-between-a-definition-and-a-declaration) – doctorlove Feb 12 '18 at 10:27
  • I added a flag for duplicate. – migu Feb 12 '18 at 10:28
  • @doctorlove I read the link you posted before I posted my question I read what is the definition and declaration but my question is more specific than the general notions ...My question is given the understanding of char ch; is definition and declaration how one cannot define but only declared this variable. I thought the use of extern is if there is a global variable that you don't want to be hidden. Sorry for the inconvenience – chaviaras michalis Feb 12 '18 at 10:42
  • 1
    Just `extern` does it - see my answer. We would stray into `static` as well. In all honesty, just grok that you can declare things without defining them. If you do both (and make sure you initialise them) you will avoid a load of problems. – doctorlove Feb 12 '18 at 11:26

1 Answers1

1

I suspect the information to answer this is in other questions, but it's explicitly asking how to change from the definition to just a declaration, so here's one way:

char ch;

defines a char, without initialising it (except for some contexts that take us to another question).

extern char ch;

declares there is a charcalled ch somewhere. The linker will have to find it.

You can do likewise with the other lines of code.

doctorlove
  • 17,477
  • 2
  • 41
  • 57