Viewing 40 posts - 1 through 40 (of 46 total)
  • Beginner's C++ help – function order
  • PJay
    Free Member

    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 E 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 Main() 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 main() (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 void 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.

    aracer
    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:

    void foo(int a);

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

    void foo(int a)
    {
    printf("%d", a);
    }

    GrahamS
    Full Member

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

    Basically, no.

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

    So you might have..


    // 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);
    }

    GrahamS
    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.

    aracer
    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!)

    porterclough
    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.

    coffeeking
    Free Member

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

    Amen. But fun, all the same.

    PJay
    Free Member

    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 int myfunction(), that function must return an integer and accepts no parameters; the prior declaration presumably needs to be mirrored in the actual function signature?

    GrahamS
    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.

    aracer
    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:

    using System

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

    prog.foo(3);
    }

    void foo(int a)
    {
    Console.WriteLine(a);
    }
    }

    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!

    elliptic
    Free Member

    What they all said.

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

    // declaration
    int myfunction(void);
    [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.

    joemarshall
    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

    GrahamS
    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)

    aracer
    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?

    elliptic
    Free Member

    embedded C++

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

    porterclough
    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.

    PJay
    Free Member

    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!

    GrahamS
    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

    al2000
    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'..

    PJay
    Free Member

    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'.

    GrahamS
    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++

    simonfbarnes
    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 🙂

    aracer
    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.

    PJay
    Free Member

    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.

    simonfbarnes
    Free Member

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

    porterclough
    Free Member

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

    GrahamS
    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:

    In fact, just stick to the bits of C++ defined in here:

    😉

    PJay
    Free Member

    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.

    llama
    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 headfeck.

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

    IA
    Full 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?

    GrahamS
    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.

    llama
    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 ….

    aracer
    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.

    aracer
    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.

    llama
    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++.

    AdamW
    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.

    llama
    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.

    IA
    Full 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.

    aracer
    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.

    GrahamS
    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?

    {is this the geekiest thread ever on STW?}

    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)

Viewing 40 posts - 1 through 40 (of 46 total)

The topic ‘Beginner's C++ help – function order’ is closed to new replies.