Beginner's C++...
 

[Closed] Beginner's C++ help - function order

45 Posts
12 Users
0 Reactions
123 Views
 PJay
Posts: 4897
Free Member
Topic starter
 

Many years ago I used to rather enjoy tinkering with computer programming (I was never any good but that wasn't really the point). I learnt using Basic, had some Cobol training, tinkered with some assembly language (badly) and (fortunately) played around with a language called [b]E[/b] on the Commodore Amiga (which I think was based on C and was an object orientated, function based, compiled language on a GIMP multitasking system, so I'm not as completely in the dark as I would be coming to C++ from, say, Sinclair Basic).

That was all a long time ago (it's probably about 15 years since I played around with the E language) but I've decided to see if I can re-ingnite that interest by playing around with C++ (with no other purpose that to have some fun and perhaps learn a useful, if limited, skill). So, I'm equipped with Microsoft Visual C++ Express and a copy of Teach Yourself C++ in 24hrs by Sams. True to form I started with the "Hello World" program running as a console application - and it worked.

The next step was an introduction to functions (as I used to use in E) which is where I ran into my first issue. The demo function program simply printed "Hello World" to the console from the [b]Main()[/b] function, called a second function which printed out a second message to the console, returned and exited; simple stuff. Rather than type it verbatim from the book I set it up myself and it went a bit wrong. In the book example the called function came first in the source code, followed by [b]main()[/b] (although I don't remember any reason being given to explain this). There were 2 errors, the first was obvious, despite definining the called function as [b]void[/b] I tried to return 0 (I don't think that E required parameters to be defined) and was easily sorted. The second had me a bit flumoxed and said that the function identifier wasn't defined (for the called function) on the line where it was called. After much checking that I'd got the function name in the call line identical to the function name in the signature I was getting a bit flustered but decided to mirror the book example and put the called function first in the source code - lo and behold, it worked.

So the compiler choked trying to call a function that wasn't defined at the point of being called and raised an error but, interestingly, then continued with the compile and then complained (initially) that the called function was a void function returning a value, so it clearly realised that the called function was there and was a function, and so should have had all the information necessary to successfully compile the program, but didn't.

Now E (and the assemblers I've played with) was, if I remember rightly, described as two pass, in that the compiler parsed the source code in two distinct phases; part of the function of the first pass was to identify function names (or in the case of assemblers, lables) for the second pass in which the actual compiling occured. Microsoft Visual C++ appears to compile in one pass.

I'm going on a bit but essentially I wanted to know whether I have to arrange all my functions in a C++ program's source code so that they are arranged in an order where they're defined prior to the first instance of them being called - essentially putting main() at the end of the program in order for the compile to complete. In E I always put the main() function first and called functions below this (possibly a hangover from interpreted Basic which program execution always began from the first line of source code). Perhaps it's considered bad practice to define functions after the first instance of they're being called and C++ forces this order to encourage a certain thought process to occur before coding, but the blurb in the introduction to the C++ book suggested that C++ was meant to be flexible to allow programs to program in the style they wished. Perhaps it's a foible of Microsoft C++ (the book works with a Borland compiler) and there's a way to set it up as a two pass compiler.

Anyway, do I need to stick to this way of ordering source code or should I be able to start my source code with main() and stick my function definitions where I like (in E I'm pretty sure that the idea of functions as self contained elements meant that they could go in in any order you liked)?

I was always a pretty poor hobbyist programer and I'll probably never write anything useful (and there's certainly a long way to go and a lot to learn from "Hello Word!" in a console window to a windowed Windows application using the .net framework - and I've now idea about this) but I didn't expect to get quite so muddle at the "Hello World" stage.


 
Posted : 27/01/2010 5:35 pm
Posts: 0
Free Member
 

Apologies if I've missed some important point - I rather skimmed that long post.

Yes, you do have to define your functions before you call them in C++, since the compiler only does a single pass. But that doesn't mean you have to put them in order - instead you declare the function header in advance. Normally you use a header file for this - you can do it all in a single file if you're just doing simple stuff, but using a header file is a good practice to get into and it hides all this stuff away. Anyway, what you want is something like:

[code]void foo(int a);

void main(int argc, char **argv)
{
foo(3);
...
}

void foo(int a)
{
printf("%d", a);
}[/code]


 
Posted : 27/01/2010 5:41 pm
Posts: 31206
Full Member
 

Bloody hell that's a long story for a short question.

Basically, no.

You can [b]declare[/b] a function (prototype), either in the same file or in a header file. Then you can use it in the file before you [b]define[/b] it.

So you might have..

[code]
// This is the prototype: the function declaration
void myfunction(int a_param);
 
// This the MAIN the startpoint of the program
int main(int argc, char *argv[])
{
    myfunction(3);
   myfunction(4);
}
 
// This is function definition
void myfunction(int a_param)
{
   printf("You passed: %d", a_param);
}
[/code]


 
Posted : 27/01/2010 5:46 pm
Posts: 31206
Full Member
 

By the way, C++ is a horrible language to try and teach yourself.

I recommend C# or Java instead. Far more modern and far less weirdness.


 
Posted : 27/01/2010 5:50 pm
Posts: 0
Free Member
 

It would appear I code faster, but Graham writes code which is more readable, given the remarkable similarity in functionality of our examples (I code like that when I get paid for it!)


 
Posted : 27/01/2010 5:52 pm
Posts: 0
Free Member
 

As above, or if you can't be bothered with separate declarations, then you are right, your main() would be the last func in your file and the functions it calls above - i.e., upside down to what you have done.


 
Posted : 27/01/2010 5:52 pm
Posts: 17
Free Member
 

By the way, C++ is a horrible language to try and teach yourself

Amen. But fun, all the same.


 
Posted : 27/01/2010 5:53 pm
 PJay
Posts: 4897
Free Member
Topic starter
 

Sorry, yes the post did rather grow somewhat, but that's exactly what I was asking, I didn't realise that you could define the function name before coding the function itself. Thanks for that, I shall play around some more. Persumably the type you define for the function name (void, int etc.) relates to any value the function may return so if I define a function name [b]int myfunction()[/b], that function must return an integer and accepts no parameters; the prior declaration presumably needs to be mirrored in the actual function signature?


 
Posted : 27/01/2010 5:54 pm
Posts: 31206
Full Member
 

It would appear I code faster, but Graham writes code which is more readable

I had to go look up "definition" and "declaration" to make sure I didn't teach him it the wrong way round 😳

the prior declaration presumably needs to be mirrored in the actual function signature

Yep. It will complain if it doesn't.


 
Posted : 27/01/2010 6:01 pm
Posts: 0
Free Member
 

Having dabbled in C# (I did write some C# code which will go into a production system last week, but it was mainly a cut and paste job), I'm less than convinced by the huge advantage of C# over C++. Surely an awful lot of the code looks remarkably the same? Meanwhile, the simplest way I could find of coding our example in C# is:

[code]using System

class Program
{
static void Main(strings[] args)
{
Program prog = new Program();

prog.foo(3);
}

void foo(int a)
{
Console.WriteLine(a);
}
}[/code]

Now granted you don't have to predeclare the function, and I don't know C# that well so it may be possible to do better, but I'm not convinced that's easier!


 
Posted : 27/01/2010 6:03 pm
Posts: 106
Free Member
 

What they all said.

The return type and arguments in the declaration [b]must[/b] match the definition an for a function taking no arguments you should use "void" eg:
[code]
// declaration
int myfunction(void);
[/code][code]
// definition
int myfunction(void)
{
return 42;
}
[/code]

This mechanism also lets you build programs from multiple source files: you can define a function in source file A, then declare and call it in source file B.

The main reason for header files is to hold common function declarations and other stuff that needs to be visible to multiple source files.


 
Posted : 27/01/2010 6:06 pm
Posts: 0
Free Member
 

If you wanted a language that is easy to learn, hard to get wrong, and still pretty powerful, then python would do the job. But it is far less of a learning challenge than C++.

Whatever you do, don't learn java, it is a sick abomination of a system - a sort of okay base language spoilt by all the really bad standard classes, and the horrible way that Sun choose to distribute it.

Joe


 
Posted : 27/01/2010 6:06 pm
Posts: 31206
Full Member
 

I don't know C# that well so it may be possible to do better, but I'm not convinced that's easier!

Yeah but how many production systems consist of a "Hello World" like that?

Most things are Object Oriented these days and classes, interfaces, generics, collections, functors etc are all much easier and more consistent in C#.

(I'm writing embedded C++ at the moment, and after coming from C# on my last project it is really doing my head in)


 
Posted : 27/01/2010 6:06 pm
Posts: 0
Free Member
 

I had to go look up "definition" and "declaration" to make sure I didn't teach him it the wrong way round

Ah - I spend my days clicking on "Go To Declaration" and "Go To Definition", so it comes naturally.

p.s. how do you indent when using the "CODE" tags - can't get it to work for me, which leaves my code not very readable?


 
Posted : 27/01/2010 6:08 pm
Posts: 106
Free Member
 

embedded C++

Luxury! I'm writing DSP assembly (and I also maintain the assembler...)


 
Posted : 27/01/2010 6:10 pm
Posts: 0
Free Member
 

Just to clarify, the original question, though asked about C++, was actually simply about C, since it contained no object oriented stuff. C++ is just C but with object oriented syntax bolted on, in quite a messy way.

C# is probably a better way to get into object oriented programming (not that I've done much, but anything would be better than C++) since it will force you to learn to do things the right way. If you're not careful you can get in a right tangle with C++ IMHO... it makes no effort to save you from yourself.


 
Posted : 27/01/2010 6:10 pm
 PJay
Posts: 4897
Free Member
Topic starter
 

Maybe this isn't quite the sort of thing to be doing for fun! Still I'll persevere, at least beyond the "Hello World" stage.

Now printf looks familiar (from my E days I think), the Sams book has me using std::cout << "Hello World";
which is a lot harder to remember!


 
Posted : 27/01/2010 6:12 pm
Posts: 31206
Full Member
 

you can get in a right tangle with C++ IMHO... it makes no effort to save you from yourself.

As the old saying goes: "C++ gives you enough rope to shoot yourself in the foot. Twice."

p.s. how do you indent when using the "CODE" tags - can't get it to work for me, which leaves my code not very readable?

Yeah I edited multiple times before I discovered that it switched off CODE if you leave a blank line and it throws away all indents. Sprinkling & nbsp; about sorted it out


 
Posted : 27/01/2010 6:15 pm
Posts: 19
Full Member
 

If you're doing it as a hobby, C++ isn't the language to learn - it's very much an all or nothing language, if only so you can work out which parts not to touch with a bargepole.

C# on the other hand would be a good choice - using windows forms, you can chuck together some fairly complex applications quite easily, and learn as you go. It will also give you a nice grounding in object oriented programming.

As has been mentioned, you can get yourself in a proper mess with C++, but if you want to have a crack anyway (and chapeau! if you do..) pick up a copy of Scott Meyer's Effective C++. I've heard it described as 'a useful guide on how to move your foot slightly out of the way of the C++ Gatling Gun you're waving around'..


 
Posted : 27/01/2010 7:05 pm
 PJay
Posts: 4897
Free Member
Topic starter
 

It sounds like I might be better ditching the C++ book and trying C#, a bit of a shame since I've just bought the book. I probably should have done a bit more research but from what research I did do I got the impression that C# was a Microsoft created lanague designed specifically for the .net framework in Windows and thought that it might not be the best option and perhaps a bit limited. C++ seems to be a hugely popular language and perhaps I assumed that that made it 'better'.


 
Posted : 27/01/2010 7:36 pm
Posts: 31206
Full Member
 

C# was a Microsoft created lanague designed specifically for the .net framework in Windows

It is. Good language though.

If you want something portable then you could start with C. It's a little old and not object-oriented, but much easier to learn than C++


 
Posted : 28/01/2010 12:20 am
Posts: 0
Free Member
 

The return type and arguments in the declaration must match the definition an for a function taking no arguments you should use "void"

well, in fact the compiler will pretend you put foo(void) if you just have foo(). Also, as an aside, you can actually call a function with an arbitrary, variable collection of arguments of any type using foofoo( ... ) as the declaration 🙂


 
Posted : 28/01/2010 12:41 am
Posts: 0
Free Member
 

I got the impression that C# was a Microsoft created lanague designed specifically for the .net framework in Windows and thought that it might not be the best option and perhaps a bit limited.

Which is at least one reason why C++ still exists. Unlike Graham I'm very happy to be back on a project doing embedded C++, having just come from interfacing MS unmanaged C++ via MS managed C++ into C#. Now that really did my head in!

Still don't see what's wrong with C++ for a hobbyist - most of the problems surely come when you get into large projects and maintaining other people's code. If you follow the basic rules (just as you have to for C#) it should all work. The fact you can do lots of stupid stuff with pointers doesn't mean you have to.


 
Posted : 28/01/2010 1:03 am
 PJay
Posts: 4897
Free Member
Topic starter
 

Well, it's all a bit confusing. Although I was never any good at coding, I did enjoy it and fancied having another go - for fun rather than anything else. The problem is that there are such a lot of different technolgies (I did think of trying PHP as I manage a small website for a local charity). I plumped for C++ as I thought that it was widely used and popular and may serve as an introduction to other languages (I still think that PHP would be something to play around with as I could actually do something with it). Unless I'm missing something though, Microsoft Visual C++ Express seem like a glorified text editor and doesn't have anything like C#'s forms for gui design (which looks really handy); I assume you have to buy the full version to get something similar in C++. I dread to think what coding windows, menus etc. must be like.

Perhaps I should think a bit more before wading in.


 
Posted : 28/01/2010 2:01 pm
Posts: 0
Free Member
 

C++ and PHP are quite different, one compiled, the other interpreted, and intended for different purposes. I use both all the time


 
Posted : 28/01/2010 2:05 pm
Posts: 0
Free Member
 

Might be worth checking out something like Ruby or Python too.


 
Posted : 28/01/2010 2:07 pm
Posts: 31206
Full Member
 

The fact you can do lots of stupid stuff with pointers doesn't mean you have to.

True, I'd also stay away from:

templates
multiple inheritance
const correctness
operator overloading
mixing object-oriented and procedural programming
multi-threading
C linkage
copy constructors

And anything in here:
[img] http://www.informit.com/ShowCover.aspx?isbn=0321125185&type=f [/img]

In fact, just stick to the bits of C++ defined in here:
[img] [/img]

😉


 
Posted : 28/01/2010 2:13 pm
 PJay
Posts: 4897
Free Member
Topic starter
 

I appreciate that C++ and PHP are different, it's just that there appears to be a whole slew of languages out there and picking one to learn seems tricky; I'd probably be able to do something useful with PHP (which wouldn't necessarily be the case with C++, I'm not sure I'd ever be able to manage to code a useful Windows application). I shall think some more.


 
Posted : 28/01/2010 2:15 pm
Posts: 3300
Full Member
 

oh good a programming thread!

Never heard of E

C++ is nasty. I don't see the point in learning it starting now, even for a hobby. I can't think of any hobby applications where its use is required, at a push plain C would be a better bet for a novice, but nowadays with Java, C#, Python, Ruby etc etc why bother beating yourself?

I got the impression that C# was a Microsoft created lanague designed specifically for the .net framework in Windows and thought that it might not be the best option and perhaps a bit limited.

Well thats kind of true. MS created it but strictly speaking they don't own it and there are other .net runtimes out there. Some bits of Ubuntu use mono for example. Of course thats all academic as in practice MS influence the standard completely.

Microsoft Visual C++ Express seem like a glorified text editor and doesn't have anything like C#'s forms for gui design

It never really did (they are on visual studio version what now? 10?) The closest they got was MFC and that was a mile from the GUI designer for c#/vb.net. And don't even go near managed C++ cos thats a total head****.

It depends what you want to do really, but if its making windows appear on windows OS, there is nothing more productive than C#.


 
Posted : 28/01/2010 2:41 pm
 IA
Posts: 563
Free Member
 

Learn to program, not a language. Just pick a few to try out. Try some C++ (after all, you have a book) then try something completely different. How about some Haskell, Prolog or Scheme perhaps?


 
Posted : 28/01/2010 2:43 pm
Posts: 31206
Full Member
 

How about some Haskell, Prolog or Scheme perhaps?

I know them.

Never used them since Uni. **** all use for someone like the OP who wants to build his own windows apps.


 
Posted : 28/01/2010 2:51 pm
Posts: 3300
Full Member
 

Having dabbled in C# (I did write some C# code which will go into a production system last week, but it was mainly a cut and paste job), I'm less than convinced by the huge advantage of C# over C++

hmmmm hope your not working on anything important ....


 
Posted : 28/01/2010 3:07 pm
Posts: 0
Free Member
 

I can't think of any hobby applications where its use is required

Not heard of microcontrollers then (eg PIC / AVR)? I've yet to come across a C# compiler for a microcontroller / embedded processor. I suppose you can use assembler with these - which is indeed what I tend to do for home projects a lot of the time - but that's hardly something I'd recommend to a beginner!

Microsoft Visual C++ Express seem like a glorified text editor and doesn't have anything like C#'s forms for gui design

You can I think do forms in C++ in the same way as with C# with the express versions. However C++ does seem to be far more crippled in express than C# - is not a good way to learn C++, which is probably the intention of MS to steer people towards C#. Of course in full VC++ most people would use MFC with C++, which for all its limitations is quite a powerful framework.


 
Posted : 28/01/2010 3:12 pm
Posts: 0
Free Member
 

hmmmm hope your not working on anything important ....

Why? I'm very confident my code works and is properly structured. Just because I've not used the full range of what you can do with C# and only written a small bit of code doesn't mean I didn't know what I was doing with that. After all, as I mentioned before, it's not a huge leap from C++ anyway.


 
Posted : 28/01/2010 3:16 pm
Posts: 3300
Full Member
 

Not heard of microcontrollers then (eg PIC / AVR)? I

If you want to mess about with these for a hobby, have fun. I would say use C instead of C++ saving yourself from lots of pitfalls.

You can I think do forms in C++ in the same way as with C#

Using managed C++. It really is horrid, pointless, and is certainly not C++.


 
Posted : 28/01/2010 3:18 pm
Posts: 8
Free Member
 

I learned Objective C for a laugh a couple of years ago. It took a little while to work out what they were doing with it but I quite like it now.

Though only the Mac/iPod/iPhone use it though.


 
Posted : 28/01/2010 3:24 pm
Posts: 3300
Full Member
 

sorry aracer, didn't mean it that way! I'm sure you are capable and everything, but although the syntax is similar, thats about it.


 
Posted : 28/01/2010 3:25 pm
 IA
Posts: 563
Free Member
 

" **** all use for someone like the OP who wants to build his own windows apps."

They said they were just doing it for fun, I thought it might be fun to learn about different styles of programming? Doesn't sound like they are writing any windows apps just yet. So I'm guessing they're naturally interested in the puzzle/mental challenge of it all. And you get a different sort of challenge with declarative languages.


 
Posted : 28/01/2010 3:37 pm
Posts: 0
Free Member
 

Using managed C++. It really is horrid, pointless, and is certainly not C++.

Having had to use it recently I'll agree with you on that - syntax is all over the place, leading me to wish I was using C#! I once tried using C++ Forms in express, but quickly gave up - I think we also agree C++ in express is rubbish.

I would say use C instead of C++ saving yourself from lots of pitfalls.

Really? I'd have said it was a lot easier to make a mess of things with C - at least C++ imposes some structure on you. Maybe it's just me, but I don't even feel the need to do most of the things in Graham's gotcha list. Certainly no need at all to get involved in the bits which are C++ specific.

although the syntax is similar, thats about it

Being the ignoramus I am (I never claimed to know much about C# even if I am quite capable of writing working code in it) you'll have to explain to me the vast gaping differences.


 
Posted : 28/01/2010 3:42 pm
Posts: 31206
Full Member
 

Certainly no need at all to get involved in the bits which are C++ specific.

Doesn't that mean you're just writing C but using a C++ compiler?

[i]{is this the geekiest thread ever on STW?}[/i]

you'll have to explain to me the vast gaping differences.

They are many and multitudinous, but some big hitters are:

• fully object-oriented
• managed code and interoperability with other managed code (in any language) via the Common Language Runtime
• garbage collection
• no pointers (in safe code at least)
• better type safety
• interfaces
• generally much cleaner syntax (though still C-like)


 
Posted : 28/01/2010 4:12 pm
Posts: 0
Free Member
 

Ah, I didn't write that very well - I meant no need to get involved in the C++ specific bits on your gotcha list.


 
Posted : 28/01/2010 4:17 pm
Posts: 31206
Full Member
 

Still don't get you though, what do you do about those gotcha items like multi-threading and copy constructors, which you pretty much have to address to write stuff?

(Edited my last reply to answer your other question about differences between C and C# by the way)


 
Posted : 28/01/2010 4:22 pm
Posts: 3300
Full Member
 

well apart from the garbage collection / managed runtime thing a few key differences are:

no headers
no #defines
no pointers
stricter type safety
arrays are managed
strings are too
and they're unicode
objects only on heap, never stack
single inheritance
interfaces
reflection
threading
delegates
enumerators
properties
attributes
enums, null, bool are all 'official'

and a much more complete and productive standard library


 
Posted : 28/01/2010 4:27 pm
Posts: 31206
Full Member
 

Yeah, all that too 🙂

[url= http://msdn.microsoft.com/en-us/magazine/cc301520.aspx ]What You Need to Know to Move from C++ to C# (Jesse Liberty, MSDN Magazine, July 2001)[/url] (bit old but worth a read)


 
Posted : 28/01/2010 4:35 pm
Posts: 0
Free Member
 

what do you do about those gotcha items like multi-threading and copy constructors, which you pretty much have to address to write stuff?

Hmm well this is all getting a bit spread out, but I was specifically referring to the suggestion of using C instead of C++ for microcontrollers, in which case MT is irrelevant (at least in anything I've ever done), and even if it wasn't, it's not any more of an issue in C++ than in C. You don't have to use copy constructors if you don't copy objects, which I seem to manage OK without most of the time - the issue here is presumably just that you have to remember to write one?

Nothing in your list of C# differences I wasn't aware of - though I'd argue that C++ does do managed code (horrible as it might be), and interfacing with other languages, after all that's exactly what I've just been doing! I don't see anything there though to justify the assertion that only the syntax is similar either - I'd argue that in terms of writing code (rather than what goes on underneath) there are a lot more similarities than differences, at least from what I've seen - and I've been working with some quite extensive bits of C# code other people have written.


 
Posted : 28/01/2010 5:06 pm
Posts: 31206
Full Member
 

Yeah the syntax and general style makes it easy enough to jump between them if you're a decent programmer (which you obviously are) but there still some fairly fundamental differences - more than say C to C++ I'd say.


 
Posted : 28/01/2010 5:15 pm