You are not logged in.

#1 2009-09-23 20:31:34

absolutezero1287
Member
Registered: 2008-11-13
Posts: 133

Tips for someone new to C/C++

The first programming language I learned was BASH (I know...) and then I moved on to Perl. I want to learn some C/C++ but I'm having trouble getting my head around it. Any suggestions?

Offline

#2 2009-09-23 20:38:03

Atsutane
Package Maintainer (PM)
From: Germany
Registered: 2008-08-18
Posts: 96

Re: Tips for someone new to C/C++

Well it would be more helpful if you'd describe what produces problems for you,  as from that three sentences one only can give you the link to another introduction, but doesn't know if it helps you.


[blog - mostly german] - [JabberID: atsutane 0x40 freethoughts 0x2E de] - [identi.ca]

Offline

#3 2009-09-23 21:36:57

absolutezero1287
Member
Registered: 2008-11-13
Posts: 133

Re: Tips for someone new to C/C++

@Atsutane: with respect to C/C++ I'm a complete newbie so it'd be nigh impossible for me to describe what I have trouble doing.

I tried writing a simple "hello world" in C++ and gcc just returned errors. I haven't the faintest idea what I'm doing wrong. I'm just looking for any tips/books to read for someone who is struggling with C++.

Should I learn C before learning C++?

Offline

#4 2009-09-23 22:03:12

g0ju
Member
From: Chemnitz, Germany
Registered: 2009-08-08
Posts: 23

Re: Tips for someone new to C/C++

Just check your local library for some c++ books.

Offline

#5 2009-09-23 22:22:35

Sternmull
Member
Registered: 2009-09-22
Posts: 22

Re: Tips for someone new to C/C++

I dont think its a good idea to learn C before using C++. That wont make it easier. Find a good book or tutorial to get started with the basics of the C++ syntax and the typesystem. Understand what the preprocessor and the compiler do (includes, preprocessor directives, translation units, linker). Try out what you learned and use reference material to clarify questions that come up.

Start with simple console programs that use only simple datatypes and easy to use functions (calculate something with integers and floats and print its results etc.). Learn how to use a debugger to see what your code is actually doing. Then read the some input from the console. Do your calculations with the read values and print them again. Then declare some simple structures and put the integers and floats in there. Learn how contructors and destructors work and use them to initialize and deinitialize instances of your stuctures. Understand pointers. Understand "new" and "delete" and how to use them correctly. Implement some methods for your structures. Write some more complex datastructures  (at least a doubly linked list). Always use the debugger to see if the code does what you expect! Understand "const". Write some classes and understand what private/protected/public members are good for and how to use them. Move on to some reallife data structures: Use the STL to put your structures into std::vecor, std::list, std::map and other containers and do some more complex calculations. Understand iterators. Try out ineritance and virtual functions. And when you understood all parts of the language that you used so far: Write your linked list as template class so it can hold objects of any type.

I think starting early to debug your programs will help you a lot to understand what is going on. Then you dont have to guess what the program does: You can watch it and you will know fore sure what is going on. The debugger is your best friend. Watch your variables, see the callstack, set breakpoints to see when a line of code is executend and in what context it gets called.

And dont expect to learn C++ within a few weeks. The syntax is "complex" and the language has a lot of pitfalls. At the beginning you will have a lot of frustrating compiler errors. And when it compiles it will sometimes do things that you did not expected. But after you understood C++ and got exprecience in software development you will have learned a lot. Learning other languges like Java, C# will be a matter of a few days. They cant shock you when you know all pitfalls and tricks you have seen in C++ smile

Offline

#6 2009-09-23 22:31:57

Atsutane
Package Maintainer (PM)
From: Germany
Registered: 2008-08-18
Posts: 96

Re: Tips for someone new to C/C++

Well C++ was build up on C, but you don't need to learn C if you want to write your later code in C++ as nearly everything was replaced by the paradigmns of object orientation with classes and methods, so I can only say the same as g0ju, go to your library and get one or two books from there it'll help you more.

For your current problem: If you've checked that the base-devel group is installed and your source is correct, then compile C++ Code with g++ instead of gcc, as that's the C++ compiler, using gcc forces you to link the code against the C++ library.


[blog - mostly german] - [JabberID: atsutane 0x40 freethoughts 0x2E de] - [identi.ca]

Offline

#7 2009-09-23 22:33:41

gnud
Member
Registered: 2005-11-27
Posts: 182

Re: Tips for someone new to C/C++

I think many newbie C/C++-problems stem from a lack of understanding of the compilation process.

Compilation is broken into two main phases: Compiling and linking.

When compiling, your source code is transformed into so-called object code. Any syntax errors or type errors are caught during this phase. The result is an object file (whatever.o). This file can not be run as a program - it must be linked.

Linking produces a program or library from one or more object files. During this phase, use of external libraries (like libc) is resolved. You might get errors if a function you try to use, is not found, for example.


Now, let's walk through a very simple program step by step. This program probably have some weak points, I kinda made it up on the spot smile

#include <stdio.h>
#include <stdlib.h>
#include <math.h>


int main(int argc, char** argv)
{
    double deg, rad; /* a double is a way to work with fractional numbers on computers. It's not completely accurate, but it's relatively fast. The inaccuracies does usually not matter, unless you are working with rockets, medicine or finance. */

    int i; /* we use this counter for our loop */

    
    if(argc < 2) {
        printf("Usage: %s [number] ...\n", argv[0]);
        return 1; /* It's standard to return a number > 0 (often 1) on failure */
    }


    for(i = 1; i < argc; ++i) {
        deg = atof(argv[i]);
        if(deg != deg) { /* NaN, not a number, is not equal to itself */
            printf("The %d. number was not valid\n", i);
            continue; /* Go to next value of "i", skip the rest of this pass through the loop */
        }

        /* Let's convert the degrees into radians */
        rad = deg * (M_PI / 180); /* The M_PI constant is defined in math.h */
        
        rad = sin(rad);
        /* and lets convert back into degrees */
        rad = rad * (180 / M_PI);

        printf("The sine of %f is %f\n", deg, rad);
    }
    return 0; /* It's standard to return 0 on success */
}

This idiotic little program can print the sines of a list of numbers.
First, copy the code into a file, and name it, for example, sine.c

Now, let's compile it:

$ gcc -c sine.c

Here, we ask GCC to compile (-c) the file sine.c.
This will produce an object file called sine.o

Now, let's create a program:

$ gcc -o sine sine.o

Here we ask gcc to output a file called sin (-o sine), from the object file sine.o

Ooops! This gives us the following error:

sin.o: In function `main':
sin.c:(.text+0x96): undefined reference to `sin'
collect2: ld returned 1 exit status

The function "sin", which we use, is not in any file we specify!
We use the math library (#include <math.h>), so we must tell gcc to link against the math library:

$ gcc -lm -o sine sine.o

The "-l" switch is used to tell gcc to link against a library. In this case, "-lm", the gcc linker looks for a file named "libm.so". So, to link against libfoo, I'll say "-lfoo".

Now we have a working program, which can be run like "./sine 180 270".


As you can see, I was kinda bored...

Offline

#8 2009-09-23 22:37:52

absolutezero1287
Member
Registered: 2008-11-13
Posts: 133

Re: Tips for someone new to C/C++

@Sternmull: thanks for the advice. I have some C++ books but I've never been able to get my head around them and they all use windows tools which really pisses me off. I think I'll find some tutorials online.

Offline

#9 2009-09-23 22:41:25

absolutezero1287
Member
Registered: 2008-11-13
Posts: 133

Re: Tips for someone new to C/C++

@gnud: very interesting. I think I understand things a bit better now. Thank you very much.

Offline

#10 2009-09-24 15:02:31

manx
Member
From: Staffordshire, England
Registered: 2008-09-27
Posts: 35

Re: Tips for someone new to C/C++

I bought "C++ Primer Plus" by Stephen Prata a while ago and if your serious about C/C++ i would hightly recommend you get it. Although some exposure to C would be helpful, it doesn't assume you have any prior knowledge. It takes you all the way thru programming in C/C++, starting with the compilation process, right up to the more advanced topics like OOP, Generics, Templates etc. etc.

Last edited by manx (2009-09-24 15:02:57)

Offline

#11 2009-09-24 15:27:42

Bralkein
Member
Registered: 2004-10-26
Posts: 354

Re: Tips for someone new to C/C++

C++ was the first programming language I learned and I did so from the great online book Thinking in C++ by Bruce Eckel. I found it very challenging but I learnt so much from that text. Worth a go, and it's free so there's nothing to lose but precious hours of your life!

Offline

#12 2009-09-24 15:47:32

MindTooth
Member
From: Norway
Registered: 2008-11-11
Posts: 331

Re: Tips for someone new to C/C++

May I suggest this book: http://www.amazon.com/Primer-Plus-5th-S … 0672326973
A really good one.

Birger smile

Offline

#13 2009-09-24 17:42:46

scio
Member
From: Buffalo, NY
Registered: 2008-08-05
Posts: 366

Re: Tips for someone new to C/C++

Offline

#14 2009-09-24 21:05:00

absolutezero1287
Member
Registered: 2008-11-13
Posts: 133

Re: Tips for someone new to C/C++

Thanks again everyone. I'll follow those links and read up.

Offline

#15 2009-09-24 21:08:37

bernarcher
Forum Fellow
From: Germany
Registered: 2009-02-17
Posts: 2,281

Re: Tips for someone new to C/C++

+1 for Thinking in C++
It requires some basic C knowledge, however.
Also really useful: C++ Annotations


To know or not to know ...
... the questions remain forever.

Offline

#16 2009-09-25 19:24:22

pharcyde
Member
From: Connecticut
Registered: 2009-03-13
Posts: 88

Re: Tips for someone new to C/C++

manx wrote:

I bought "C++ Primer Plus" by Stephen Prata a while ago and if your serious about C/C++ i would hightly recommend you get it. Although some exposure to C would be helpful, it doesn't assume you have any prior knowledge. It takes you all the way thru programming in C/C++, starting with the compilation process, right up to the more advanced topics like OOP, Generics, Templates etc. etc.

Seconded on this, Stephen Prata is an excellent writer.

Offline

#17 2009-09-26 03:25:30

techprophet
Member
Registered: 2008-05-13
Posts: 209

Re: Tips for someone new to C/C++

Bralkein wrote:

C++ was the first programming language I learned and I did so from the great online book Thinking in C++ by Bruce Eckel. I found it very challenging but I learnt so much from that text. Worth a go, and it's free so there's nothing to lose but precious hours of your life!

You mean that there are people who don't think in C? How do they get around the lack of linearity?

The best hello world c++ program is:

#include <iostream>

using namespace std;

int main(int argv, char *argc[])
{
    char text[6] = "hello"; // Set 'text' to "hello\0"
    cout << text << endl; // Print it out on the standard output, with and endline
    return 0; // Provide the standard SUCCESS return value
}

Then (at the CLI) to compile:

$ g++ hello.cpp -o hello
$ ./hello

Exercise: Look up the main() arguments and make it accept input from the CLI!

Offline

#18 2009-09-26 06:49:19

Trent
Member
From: Baltimore, MD (US)
Registered: 2009-04-16
Posts: 990

Re: Tips for someone new to C/C++

@techprophet:  you switched argc and argv.

Personally, I favor C, partly because my command of it is much greater than C++.  But pick one and go with it; don't mix the two around.  (Observe that gnud's listing was idiomatic C, whereas techprophet's is valid only in C++.)  I think that hideous, unmaintainable code lies ahead of the programmer who writes C in C++ (or vice versa).  This is not to say that one shouldn't learn both languages -- just that one should write idiomatic C++ when writing C++, and idiomatic C when writing C; things are so much easier to read that way.  I would recommend a beginner to pick one and learn it well before moving on to the other.

Offline

#19 2009-09-26 09:39:38

absolutezero1287
Member
Registered: 2008-11-13
Posts: 133

Re: Tips for someone new to C/C++

I'm having a bit of trouble understanding the int main(int argc, char *argv[]) bit of the a typical C program

#include <stdio.h>
int main(int argc, char *argv[])
{
      printf("Hello, you are learning C!!\n");
      return 0;
}

That's a program I got from one of the books you guys recommended. It sort of explains it in the book but I'm still having some trouble understanding it. Just in case you guys were wondering, I've decided to learn C before I learn C++.

Offline

#20 2009-09-26 09:45:44

scragar
Member
Registered: 2009-07-14
Posts: 108

Re: Tips for someone new to C/C++

Argc is the arguments count, argv is the argument values, it's an array of pointers to the c-strings(arrays of characters).

Last edited by scragar (2009-09-26 09:46:03)

Offline

#21 2009-09-26 14:41:42

Trent
Member
From: Baltimore, MD (US)
Registered: 2009-04-16
Posts: 990

Re: Tips for someone new to C/C++

Have you read much about arrays and pointers yet?  argv is an array of character pointers.  When main is invoked, argv is initialized to the command line arguments and argc is set to the number of arguments.  argv[0] is a pointer to the name with which the program was invoked, and argv[argc] is always NULL.  Here's a quick sample program, which just prints out the arguments one by one:

#include <stdio.h>

int main(int argc, char *argv[])
{
    int i;
    for (i = 0; i < argc; i++) {
        printf("argv[%d] = \"%s\"\n", i, argv[i]);
    }
    if(argv[i] == NULL) /* i == argc */
        printf("argv[%d] is NULL\n", i);
    else
        printf("argv[%d] is not NULL.\n", i);
    return 0;
}

Actually, if you don't use the arguments, this prototype is also valid:

int main(void)

If you're using gcc with all warnings enabled (which is strongly recommended), the hello world program you mentioned above should have warned you that your main function didn't use its arguments.  Use "-W -Wall" to turn on warnings.

And since this post isn't enough of a hodgepodge of random advice already, I'm going to strongly recommend you buy, borrow or check out a copy of The C Programming Language (2nd ed.), by Kernighan and Ritchie.  There's a reason they call it the "white bible".

Offline

#22 2009-09-26 16:02:03

techprophet
Member
Registered: 2008-05-13
Posts: 209

Re: Tips for someone new to C/C++

Trent wrote:

@techprophet:  you switched argc and argv.

whoops, it was late...

Listen to Trent, he looks like a smart guy.

Offline

#23 2009-09-27 02:31:06

absolutezero1287
Member
Registered: 2008-11-13
Posts: 133

Re: Tips for someone new to C/C++

Trent wrote:

Have you read much about arrays and pointers yet?  argv is an array of character pointers.  When main is invoked, argv is initialized to the command line arguments and argc is set to the number of arguments.  argv[0] is a pointer to the name with which the program was invoked, and argv[argc] is always NULL.  Here's a quick sample program, which just prints out the arguments one by one:

#include <stdio.h>

int main(int argc, char *argv[])
{
    int i;
    for (i = 0; i < argc; i++) {
        printf("argv[%d] = \"%s\"\n", i, argv[i]);
    }
    if(argv[i] == NULL) /* i == argc */
        printf("argv[%d] is NULL\n", i);
    else
        printf("argv[%d] is not NULL.\n", i);
    return 0;
}

Actually, if you don't use the arguments, this prototype is also valid:

int main(void)

If you're using gcc with all warnings enabled (which is strongly recommended), the hello world program you mentioned above should have warned you that your main function didn't use its arguments.  Use "-W -Wall" to turn on warnings.

And since this post isn't enough of a hodgepodge of random advice already, I'm going to strongly recommend you buy, borrow or check out a copy of The C Programming Language (2nd ed.), by Kernighan and Ritchie.  There's a reason they call it the "white bible".

I'll look into it, thanks.

Offline

#24 2009-09-27 09:41:35

Peasantoid
Member
Registered: 2009-04-26
Posts: 928
Website

Re: Tips for someone new to C/C++

Don't think you can get away with not freeing your pointers. Sooner or later, it will come back to bite you in the... uh... yeah.

Offline

#25 2009-09-27 18:27:53

mjsurette
Member
Registered: 2009-09-27
Posts: 1

Re: Tips for someone new to C/C++

absolutezero1287, something you should think about is that C is a proccedural language while C++ is an object-oriented language.  They require thinking about a problem in two very different ways even though they have a lot in common. 

You may want to learn C first because it is procedural, which is what you're used to.  This is your first compiled language and as you've already found, you have to learn the process as well.

As for recommendations, http://www2.its.strath.ac.uk/courses/c/ seems to cover all the basics.  It's unix-centric and even mentions make.

Good luck

Mike

Offline

Board footer

Powered by FluxBB