Newbie questions (four of them)

B

Blue Ocean

I am a freshman computer science student teaching myself how to
program in C, since my university only teaches Java for the first 1.5
years. I have one or two (or 4) small questions, because I'm finding
C much more difficult than I did the first semester of Java.

1) I have noticed that it is common for C programmers to shorten names
of functions, variables, and other things. Java's tradition (or so
I've been told) is to write descriptive names for variables that allow
for easy readability and expandability of a program. Will anyone
fault me if I get in the habit of doing this in C? If I eventually
have to have someone look at my code, will it be a problem that
capitalizations follow Java standards? Do long variable names damage
the speed of a program at runtime?

2) Are structures the closest things C has to the classes provided by
C++ and Java?

3) Do you have any general advice for making sense of header
files/preprocessor directives? Of all the things that I have seen in
C, this is the one thing that really confuses me. I have read four
different explanations of how they work, and they still trouble me
greatly. I have to use trial and error to see if what I'm doing is
correct. Do any of you all know of a website that does a really good
job of explaining preprocessor directives?

4) Any general advice for someone just starting out? Places to go,
people to see, etc.?

Thank you all for your help, in advance. I think I've followed all
the forums rules but please tell me if I have not. Thanks again.

James
 
L

Lyn Powell

Blue Ocean said:
1) I have noticed that it is common for C programmers to shorten names
of functions, variables, and other things. Java's tradition (or so
I've been told) is to write descriptive names for variables that allow
for easy readability and expandability of a program. Will anyone
fault me if I get in the habit of doing this in C?

Not at all, naming conventions are a matter of style. As long as you're
consistent, nobody has good reason to disapprove. Unless you work for them
and they require a different convention. :)
If I eventually have to have someone look at my code, will it be a problem that
capitalizations follow Java standards?

No, while C programmers typically prefer it short and sweet, I see a lot of
C++ programmers use Java-ish identifiers. I've seen the same thing in C as
well, it's up to you.
Do long variable names damage the speed of a program at runtime?

No, descriptive identifiers are only for the convenience of human readers
and don't contribute to the compiled machine code.
2) Are structures the closest things C has to the classes provided by
C++ and Java?

Pretty much, yea. Just think of C structures as being heavily restricted
classes with no concept of privacy.
3) Do you have any general advice for making sense of header
files/preprocessor directives? Of all the things that I have seen in
C, this is the one thing that really confuses me. I have read four
different explanations of how they work, and they still trouble me
greatly.

Consider the #include preprocessor directive. When you say #include
<somefile>, the entire textual contents of somefile are pasted into your
code. For example:

/* somefile.h */
int i;

/* main.c */
#include "somefile.h"

int main(void)
{
return 0;
}

After preprocessing, which is only concerned with text and nothing else,
main.c looks like this:

/* main.c */
/* somefile.h */
int i;

int main(void)
{
return 0;
}

It's textual replacement, nothing more. The <> and "" around the filename
are delimiters for the name itself, and are used to specify where to begin
searching for the file in an implementation-defined way. The concept is the
same for #define, say you have

#define MAX 10

Before compilation begins, the preprocessor replaces every occurance of MAX
with 10, so

printf("The max is: %d\n", MAX);

Will be preprocessed into

printf("The max is: %d\n", 10);

And 10 gets written to stdout.
4) Any general advice for someone just starting out? Places to go,
people to see, etc.?

You're already here, just lurk and watch the suggestions for books and such
on this newsgroup and you won't be led astray.
 
A

Arthur J. O'Dwyer

I am a freshman computer science student teaching myself how to
program in C, since my university only teaches Java for the first 1.5
years. I have one or two (or 4) small questions, because I'm finding
C much more difficult than I did the first semester of Java.

And I found Java much more exasperating in my two semesters thereof,
than I had ever found C (which has been my language of choice since
my formative years [TM]). ;-) Languages make habits. It's hard to
break them. Stick with it.
1) I have noticed that it is common for C programmers to shorten names
of functions, variables, and other things. Java's tradition (or so
I've been told) is to write descriptive names for variables that allow
for easy readability and expandability of a program.

One reason for C's style is that it was developed a lot earlier in
computer history than Java was; back when computer filenames were
six characters long and so were assembler labels. Terseness was not
only a virtue -- it was a necessity!
Once you've studied C, especially the standard library, for a little
while, you'll pick up the most common conventions. There *must* be
a list of them somewhere, like there are lists of TLAs, but I don't
know any.

i = integer index j,k = next indices after 'i'
c, ch = character
str* = function involving strings
r = reverse direction, as in 'strrchr'
(_r = reentrant, as in the non-standard 'strtok_r')
_t = type, as in 'size_t'
len, sz, n = count, size, or length

Will anyone fault me if I get in the habit of [long names] in C?
If I eventually have to have someone look at my code, will it be a
problem that capitalizations follow Java standards? Do long variable
names damage the speed of a program at runtime?

Maybe if they're being pedantic; depends on your boss; and of course
not!, respectively. Traditional C, based on the 1990 standard, has
a technical limitation of 6 non-case-sensitive significant characters per
external identifier (if I recall correctly), but no modern compiler puts
such a harsh restriction on you. But if anyone tells you that

MyClassForManipulatingBigIntegers_new()
and
MyClassForManipulatingBigIntegers_delete()

are bad names for functions, that's why. ;-)

2) Are structures the closest things C has to the classes provided by
C++ and Java?

Yes and no. Yes, 'struct' is how a C programmer creates a new
data type, most often. Structs can have data members, but no member
functions (or "methods").
But be more specific! A common idiom in C is to write code that
looks like "exploded" Java or C++ code: put the data members of your
class inside a 'struct', and then write external functions that take
a pointer to a 'struct' to simulate member functions. For example:

struct bignum
{
int sign;
int len;
char *digits;
};

int bn_init(struct bignum *p)
{
p->sign = 0;
p->len = 0;
p->digits = NULL;
return 0; /* no error encountered */
}

int bn_add(struct bignum *a, struct bignum *b, struct bignum *result)
{
[...]

See the answer to your next question.

3) Do you have any general advice for making sense of header
files/preprocessor directives? Of all the things that I have seen in
C, this is the one thing that really confuses me.

Re: header files, I think that's a FAQ. In fact, it's several FAQs.
So look at http://www.eskimo.com/~scs/C-faq/s10.html , among other
places [use Google]. I've tried to use good style in my own little
programs, which include some header files; see
http://www.contrib.andrew.cmu.edu/~ajo/free-software/
and look at some of those .h files.

Essentially, a header file contains declarations and function
prototypes needed to effectively use the module in question. Java
has no equivalent, unfortunately, although you might consider an
'interface' class to be a sort of header file, in a way, for all
classes that implement that interface.
A header file for that 'bignum' module would look something like
this.

/* This is an "inclusion guard." It is elegant enough to qualify
* as magic in my book; but unlike most magic, it's easy to figure
* out how inclusion guards work.
*/
#ifndef H_BIGNUM
#define H_BIGNUM

/* To use the bignum module, we must be able to define new objects
* of type 'struct bignum'. So the struct definition must be present
* in the header file.
*/
struct bignum
{
int sign;
int len;
char *digits;
};

/* Prototypes (declarations) for our "member" functions must go in
* the header file, too, so we can call them in our client program.
*/
int bn_init(struct bignum *p);
int bn_add(struct bignum *a, struct bignum *b, struct bignum *result);
int bn_sub(struct bignum *a, struct bignum *b, struct bignum *result);
int bn_mult(struct bignum *a, struct bignum *b, struct bignum *result);
[...]

/* This is the tail end of the inclusion guard. */
#endif


4) Any general advice for someone just starting out? Places to go,
people to see, etc.?

Buy a copy of Kernighan and Ritchie's "The C Programming Language,"
Second Edition. This is the book variously known as "K&R2", "K&R",
"TCPL", "The White Book", "The Bible", etc. It's good. Read it,
starting at the beginning, and go on until you come to the end.
Then go back to the beginning and read it again. Do the exercises,
and post your solutions here if you want help or feedback.
(Even if the first-chapter exercises look trivial to someone with
actual programming knowledge like yourself, do them! It's easiest
to build on a solid foundation.)
Search Google Groups for posts by Chris Torek, Ben Pfaff, and
Richard Heathfield. Learn about "The Rule." Notice what kinds of
questions are considered off-topic here; C doesn't directly support
nearly as much whiz-bang stuff as Java does.

Thank you all for your help, in advance. I think I've followed all
the forums rules but please tell me if I have not. Thanks again.

You're doing fine. Hope this helps.

-Arthur
 
R

Richard Heathfield

Blue said:
I am a freshman computer science student teaching myself how to
program in C, since my university only teaches Java for the first 1.5
years. I have one or two (or 4) small questions, because I'm finding
C much more difficult than I did the first semester of Java.

1) I have noticed that it is common for C programmers to shorten names
of functions, variables, and other things.

Tht's rght; 't's qt n nnyng hbt, sn't t?
Java's tradition (or so
I've been told) is to write descriptive names for variables that allow
for easy readability and expandability of a program. Will anyone
fault me if I get in the habit of doing this in C?

Whatever you do, you'll get criticised. :)

I am certainly not afraid to use long descriptive names when I feel it
appropriate. Neither should you be.
If I eventually
have to have someone look at my code, will it be a problem that
capitalizations follow Java standards?

If the capitalisations are sensible, why should they be a problem?

Here's a random snippet from my own code:

while(WNN_SUCCESS == rc && (bytes = fread(buf, 1, 3, in)) > 0)
{
*Buffer->End++ = base64[(buf[0] & 0xFC) >> 2];
*Buffer->End++ = base64[((buf[0] & 0x03) << 4) | ((buf[1] & 0xF0) >>
4)];
if(bytes > 1)
{
*Buffer->End++ = base64[((buf[1] & 0x0F) << 2) | ((buf[2] & 0xC0) >>
6)];
}
else
{
*Buffer->End++ = '=';
}
if(bytes > 2)
{
*Buffer->End++ = base64[(buf[2] & 0x3F)];
}
else
{
*Buffer->End++ = '=';
}
buf[0] = buf[1] = buf[2] = 0;
count += 4;
if(0 == count % wnn_LineLength)
{
count = 0;
rc = wnn_SVectorReplaceES(wnn_Destination, Buffer, wnn_StartPos++);
wnn_ClearString(Buffer);
}
}

I think there's quite a nice mix in there. :)

As you can see, I use long, descriptive names for functions. I use a
library-specific prefix for identifiers that are cited in headers. And I
use tiny little names for local variables where it's pretty obvious what
they are. I'm even not above using the occasional sneaky magic number when
nobody's looking.

Do long variable names damage
the speed of a program at runtime?

It's conceivable, if you're using an interpreter rather than a compiler -
but not so's you'd notice.
2) Are structures the closest things C has to the classes provided by
C++ and Java?

No. The classes provided by C++ and Java are the closest things they have to
C's structures. :)

3) Do you have any general advice for making sense of header
files/preprocessor directives?

Think of the preprocessor as a separate "compiler" which mungs the source
before giving it to the "real" compiler.
Of all the things that I have seen in
C, this is the one thing that really confuses me. I have read four
different explanations of how they work, and they still trouble me
greatly. I have to use trial and error to see if what I'm doing is
correct. Do any of you all know of a website that does a really good
job of explaining preprocessor directives?

Think lazy. The minimum knowledge you can get away with is:

1) when you use a standard library function, look up the header it's
declared in, and make sure that header is included. For example, if you are
using printf, make sure you have this line:

#include <stdio.h>

2) when you are tempted to put a magic constant number in your code, use a
#define instead:

#define PI 3.14159

and use PI, rather than 3.14159, throughout your code. The preprocessor will
rip out the PI and replace it with 3.14159. PI, in this case, is not a
variable. It just becomes another way of writing 3.14159. As tradition has
it, this makes your program easier to modify, should the ratio of diameter
to circumference ever change.

4) Any general advice for someone just starting out? Places to go,
people to see, etc.?

comp.lang.c

C FAQ: http://www.eskimo.com/~scs/C-faq/top.html

"The C Programming Language", 2nd edition, Kernighan and Ritchie

Undernet #c :)
Thank you all for your help, in advance. I think I've followed all
the forums rules but please tell me if I have not. Thanks again.

You look like you're doing fine so far.
 
K

Keith Thompson

Lyn Powell said:
Consider the #include preprocessor directive. When you say #include
<somefile>, the entire textual contents of somefile are pasted into your
code. For example:

/* somefile.h */
int i;

/* main.c */
#include "somefile.h"

int main(void)
{
return 0;
}

That's legal, but it's a bad idea to put data definitions in a header
file. Think about what happens if the same .h file is included from
two .c different files.

You can define i ("int i;") in one and only one .c file, and declare
it ("extern int i;") in the corresponding .h file.

(Better yet, avoid global data whenever possible.)
 
S

Sidney Cadot

Blue said:
I am a freshman computer science student teaching myself how to
program in C, since my university only teaches Java for the first 1.5
years. I have one or two (or 4) small questions, because I'm finding
C much more difficult than I did the first semester of Java.

1) I have noticed that it is common for C programmers to shorten names
of functions, variables, and other things. Java's tradition (or so
I've been told) is to write descriptive names for variables that allow
for easy readability and expandability of a program. Will anyone
fault me if I get in the habit of doing this in C?

Readability is favoured in any language, but it is probably true that C
tradition is to be a bit terser than Java. Part of this comes from the
examples set out by their respective Standard Libraries.

Another thing is capitalization, this is probably more extensively used
in Java (and most other OO-languages, for that matter), than C.

All this is in large part a matter of taste... It would probably be a
good idea to just have a look at a lot of C programs to get a taste for
what is considered good practice (although this differs, of course).
If I eventually
have to have someone look at my code, will it be a problem that
capitalizations follow Java standards?

Depends on where you do it. If you were a colleague of mine, I'd try to
talk you out of it ;-)
Do long variable names damage the speed of a program at runtime?

No. Depending on the compiler options (debug information), long
variables /may/ impact the executable size. Also, to be portable, bear
in mind that the C standard prescribes rather low limits on significant
characters in an identifier (31 for external identifiers, 63 for
internal identifiers, in C99).
2) Are structures the closest things C has to the classes provided by
C++ and Java?

Yes; a C struct is comparable to a Java class with only public data members.

On a certain level of abstraction, classes can be viewed as a way of
grouping "structs" and functions that act on them together. In fact, as
you may know, in C++ "structs" /can/ have member functions; in fact, the
only difference between structs and classes in C++ is that in a struct,
all members are public by default. (This is not relevant to C, but
perhaps useful to bear in mind, to get the relationship between structs
and classes clearly into view).
3) Do you have any general advice for making sense of header
files/preprocessor directives?

My advice would be: try to understand the compiler chain. Although the C
standard prescribes preciously little about this, you would typically
find that a C compiler works in several stages on a source file to
produce an executable file:

1) pre-processor: expands #... directives, comments
2) compiler (proper): transforms code to assembly
3) assembler: makes linkeable "object" files
4) linker: glues several object files into an executable

This process is normally performed start-to-finish, but any modern
compiler will have options to stop the translation after any of these
steps. This can be a very instructive exercise.

Your problem seems to lie in step #1, the preprocessor. One thing you
really need to keep in mind is that it can only do rather simple
transformations (such as macro expansions, and verbatim inclusion of
other files), and it knows next to nothing about C (other than what an
identifier looks like).

What to put in header files is in principle arbitrary (since #include
does a verbatim inclusion), although a rather clear convention has emerged.

To understand the convention, it is important to understand the
distinction between the "declaration" and the "definition" of something;
the declaration states 'what it looks like', and gives enough
information to use something from the outside (e.g., types of
parameters); while the definition of something corresponds to the "how":
the implementation.

This takes some getting used to, since (in Java) the declaration and
definition are usually the same thing.

Example:

/* File: fib.h
a declaration; in casu, a function prototype */

int fib(const int n);

/* End of fib.h */

/* File: fib.c
a definition (implementation). Note the inclusion of the header file,
the compiler will check correspondence between declared prototype and
definition */

#include "fib.h"

int fib(const int n)
{
return (n<2) ? n : fib(n-1)+fib(n-2);
}

/* End of fib.c */

Normally, you put the public declarations of some code in a header (.h)
file, and the private declarations (and the definitions of both public
and private things) in an accompanying C file.
Of all the things that I have seen in
C, this is the one thing that really confuses me. I have read four
different explanations of how they work, and they still trouble me
greatly. I have to use trial and error to see if what I'm doing is
correct. Do any of you all know of a website that does a really good
job of explaining preprocessor directives?

No tips for that, other than that it may be useful to experiment a bit
with the stand-alone C preprocessor (traditionally called 'cpp' on
Unix/Linux systems).

Although I can understand where the confusion comes from (the
preprocessor has no counterpart in Java), it may be reassuring that it
is really quite simple. At first, don't get intimidated by the details
of the preprocessor, just make sure you understand #define, #undef, and
#include. This suffices for 95+% of cases.

4) Any general advice for someone just starting out? Places to go,
people to see, etc.?

For a real thorough understanding, you could consider getting the
standard (online electronic version of the C99 standard is USD 18).

Other good books are listed in the FAQ.

Furthermore, this forum is a great place to ask questions concerning
anything related to C (standard C that is, as soon as you deviate to
platform specifics you will be told in no uncertain terms). Make the
effort to check the FAQ first, and if that doesn't help, there's bound
to be people here that can assist.
Thank you all for your help, in advance. I think I've followed all
the forums rules but please tell me if I have not. Thanks again.

Good luck... Learning C is not easy, but it can be a rewarding
experience. Unlike in Java, there is just a very thin layer between the
bare metal and the language. I for one am conviced that learning C will
help your Java skills as well, as you should get a better grasp on what
goes on "below the hood" of the Java compiler and VM.

Best regards,

Sidney
 
A

Artie Gold

Blue said:
I am a freshman computer science student teaching myself how to
program in C, since my university only teaches Java for the first 1.5
years. I have one or two (or 4) small questions, because I'm finding
C much more difficult than I did the first semester of Java.

Fair enough.
C is a little bit `closer to the metal' as it were; some find it more
difficult, some find it easier. YMMV. ;-)
1) I have noticed that it is common for C programmers to shorten names
of functions, variables, and other things. Java's tradition (or so
I've been told) is to write descriptive names for variables that allow
for easy readability and expandability of a program. Will anyone
fault me if I get in the habit of doing this in C? If I eventually
have to have someone look at my code, will it be a problem that
capitalizations follow Java standards? Do long variable names damage
the speed of a program at runtime?

First of all, note that whatever naming scheme you choose will have no
effect on the runtime efficiency of your program -- by the time you run
it, they are effectively gone. For the time being, use whatever style
you feel comfortable with. This may change if and when you're working on
a project with other programmers; at that point having a consistent
approach will be important.
2) Are structures the closest things C has to the classes provided by
C++ and Java?

Yes, that is correct. Unlike the other two languages you've mentioned, C
does not support the object-oriented paradigm directly.
3) Do you have any general advice for making sense of header
files/preprocessor directives? Of all the things that I have seen in
C, this is the one thing that really confuses me. I have read four
different explanations of how they work, and they still trouble me
greatly. I have to use trial and error to see if what I'm doing is
correct. Do any of you all know of a website that does a really good
job of explaining preprocessor directives?

In general, don't worry about them, at least at this point -- with the
exception of include guards, which are used to ensure that a header is
not included more than once within a compilation unit.

For example, in a header you will often see something like:

#ifndef SOMETHING_H
#define SOMETHING_H

.... various declarations...
#endif

Other than that, most directives are used either to deal with platform
specificities on different platforms or to selectively include
declarations or not depending on how the header is to be used.

Since at this point you should be concentrating on learning ISO standard
C, you needn't worry about such things.
4) Any general advice for someone just starting out? Places to go,
people to see, etc.?

....and miles to go before you sleep...

Seriously though, READ THE FAQ (sorry for yelling). It has pointers to
various sites that can be helpful. One notable one is
http://www.accu.org, which has, among other things, reviews of various
books about C. There are a lot of them out there -- unfortunately, many
of them will either teach you bad habits that are hard to unlearn or
present code that is directly contrary to the standard.

The other place for you is which, as its title
suggests, is geared toward beginners.
Thank you all for your help, in advance. I think I've followed all
the forums rules but please tell me if I have not. Thanks again.
Well, though you are perhaps at the fringes of topicality (as questions
more directly about C constructs and the like are the *really* topical
questions), you are being so damn *polite*, who could complain? ;-)

Welcome aboard.

HTH,
--ag
 
C

CBFalconer

Blue said:
I am a freshman computer science student teaching myself how to
program in C, since my university only teaches Java for the first 1.5
years. I have one or two (or 4) small questions, because I'm finding
C much more difficult than I did the first semester of Java.

C is primarily a procedural language. Java is object oriented. C
can largely implement Java, but not the converse. Read K&R II.
1) I have noticed that it is common for C programmers to shorten names
of functions, variables, and other things. Java's tradition (or so
I've been told) is to write descriptive names for variables that allow
for easy readability and expandability of a program. Will anyone
fault me if I get in the habit of doing this in C? If I eventually
have to have someone look at my code, will it be a problem that
capitalizations follow Java standards? Do long variable names damage
the speed of a program at runtime?

Very old systems had limits as to name length, especially external
name lengths. To all practical purposes they are all gone now.
Names do not survive into the executable code, although they may
show up in debugging symbol tables, so they don't affect anything
except comprehensibility.

C programmers usually follow the practice that CAPS is something
#defined, and other things are primarily lower case.
2) Are structures the closest things C has to the classes provided by
C++ and Java?

Yes. You can build anything out of them.
3) Do you have any general advice for making sense of header
files/preprocessor directives? Of all the things that I have seen in
C, this is the one thing that really confuses me. I have read four
different explanations of how they work, and they still trouble me
greatly. I have to use trial and error to see if what I'm doing is
correct. Do any of you all know of a website that does a really good
job of explaining preprocessor directives?

Headers, when #included, just inject text. This makes many forms
of misuse possible. I advise creating a header (or more) for each
source file, and its sole purpose is to expose certain aspects of
that source (e.g. function names, static storage class variable,
macros) to the world. Ensure nothing else is exposed. This helps
greatly in controlling visibility and eventual upkeep.
4) Any general advice for someone just starting out? Places to go,
people to see, etc.?

You are already there. Buy K&R if you don't already have it.
 
A

Arthur J. O'Dwyer

No tips for that, other than that it may be useful to experiment a bit
with the stand-alone C preprocessor (traditionally called 'cpp' on
Unix/Linux systems).

Although I can understand where the confusion comes from (the
preprocessor has no counterpart in Java),

An amusing anecdote: While Java doesn't have a built-in preprocessor,
there's nothing that says you can't preprocess Java code anyway! Last
year, for a Java-taught class, we had to implement a board game for which
it made sense to use "bitboards". But with no preprocessor, it would have
been either tedious or inefficient to do the code in pure Java by hand.
So I coded up the class using a set of #defines, ran it through 'cpp',
and used that instead!
[J]ust make sure you understand #define, #undef, and
#include. This suffices for 95+% of cases.

Except for the inclusion guards in a header file, which require at
least the knowledge of how to spell #ifndef and #endif, if not a
complete understanding of why they work.

-Arthur
 
D

Dave Vandervies

Blue Ocean wrote:

Yes. You can build anything out of them.

Note that this doesn't necessarily mean you'd want to.

By putting function pointers in your structs and passing the "this"
pointer explicitly, you can make your C look a lot like C++ or Java,
but it gets Rather Ugly and it's easy to lose track of what you're doing
and introduce bugs:
--------
#include <stdio.h>

/*You do this part once:*/
struct foo
{
void (*print)(struct foo *this);
union
{
int i;
double d;
} value;
};

void print_int(struct foo *this)
{
printf("%d\n",this->value.i);
}
void print_double(struct foo *this)
{
printf("%g\n",this->value.d);
}

/*Now (assuming the struct is set up properly) we can do a polymorphic
function call by calling through f->print:
*/
void print_foo_value(struct foo *f)
{
f->print(f);
}

/*And then you do this part everywhere you want to use your "class":*/
int main(void)
{
struct foo double_foo,int_foo;

double_foo.print=print_double;
double_foo.value.d=17.42;

int_foo.print=print_int;
int_foo.value.i=91;

print_foo_value(&double_foo);
print_foo_value(&int_foo);

return 0;
}
--------

But, unless you really need to do this in C (and it's extremely rare
to neither have a better way to do it in C nor have the option of using
another language), C++ is best written in C++, and Java is best written
in Java:
--------
/*Warning: C++ code. Topic police, avert thine eyes.*/
#include <iostream>

/*You do this part once:*/
class foo
{
public:
virtual void print() const =0;
};

class foo_double:public foo
{
double val;
public:
foo_double(double d):val(d) {}
virtual void print() const {std::cout<<val<<std::endl;}
};

class foo_int:public foo
{
int val;
public:
foo_int(int d):val(d) {}
virtual void print() const {std::cout<<val<<std::endl;}
};

void print_foo_value(const foo& my_foo) {my_foo.print();}

/*And then you do this part everywhere you want to use your class:*/
int main(void)
{
/*Look how much of the stuff the C main above was doing fgets
taken care of by the C++ compiler
*/
foo_double my_foo_double(17.42);
foo_int my_foo_int(91);

print_foo_value(my_foo_double);
print_foo_value(my_foo_int);
}
--------


dave

--
Dave Vandervies (e-mail address removed)
Why do lemmings run off the edge of a cliff?
Because the filmmaker's assistant was chasing them toward it?
--Stephen Edwards and Anthony de Boer in the scary devil monastery
 
E

E. Robert Tisdale

B. O. said:
1) I have noticed that it is common for C programmers
to shorten names of functions, variables, and other things.
Java's tradition (or so I've been told)
is to write descriptive names for variables
that allow for easy readability and expandability of a program.

Actually, it is a COBOL programmer's tradition.
Will anyone fault me if I get in the habit of doing this in C?

I won't.

Use long names for global functions and constants.
Don't use global variables.

Use short, descriptive words for function object names:

double Force(double mass, double acceleration) {
return mass*acceleration;
}

You can use abbreviations if you annotate them properly

double F( // Force
double m, // mass
double a // acceleration
) {
return m*a;
}

Decompose functions and structs into smaller modules
so that you can reuse names in enclosed scopes.
If I eventually have to have someone look at my code,
will it be a problem that capitalizations follow Java standards?
No.

Do long variable names damage the speed of a program at runtime?
No.

2) Are structures
the closest things C has to the classes provided by C++ and Java?

Yes. But they are not very close.
3) Do you have any general advice
for making sense of header files/preprocessor directives?
Of all the things that I have seen in C,
this is the one thing that really confuses me.
I have read four different explanations of how they work
and they still trouble me greatly.
I have to use trial and error to see if what I'm doing is correct.
Do any of you all know of a website
that does a really good job of explaining preprocessor directives?

A header file compensates for the lack of *modules* in C (and C++).
A header file should be

1. self-contained (self-sufficient) and
2. idempotent.

http://www.atnf.csiro.au/computing/software/sol2docs/manuals/c++/prog_guide/Program.html
 
D

Dave Vandervies

So far so good...


I find it hard to believe.

It would be rather beyond the scope of a student project, but I would
expect that a sufficiently enthusiastic (or masochistic) C programmer
would be able to implement a Java compiler and JVM entirely in C
(though not the entire Java class library, but even there the parts
that don't have equivalents in C could be faked in C or passed on to
platform-specific extensions).

Except for the aforementioned bits of the class library that aren't
found in C, it would also be possible to write a Java-to-C compiler that
outputs standard C. (I don't know why anyone would bother, and it would
have a few Rather Ugly bits in both the translator and the generated C
(f'rexample, exception handling), but it could be done[1].)

As far as the converse goes, it would be equally possible for a
sufficiently enthusiastic (or masochistic) Java programmer to implement
a C virtual machine and a compiler that targeted that CVM, but the JVM
restricts some operations vital to C (such as inspecting any data memory
as a bag of unsigned char) and that would make a C-to-Java translator
Highly Nontrivial, probably to the point of being impossible.

Does K&R2 state that?

K&R2 tells you everything you need to know about C to do the above,
and I've heard claims that their exercises walk you through some of the
basics of building a compiler (useful for the aforementioned Java-to-C
compiler) as well.


dave

[1] Random thought: The GCC people have a Java-to-native code translator.
Has anybody tried to implement a standard C back-end for GCC?
That would give us the Java to C translator.

--
Dave Vandervies (e-mail address removed)
Why do lemmings run off the edge of a cliff?
Because the filmmaker's assistant was chasing them toward it?
--Stephen Edwards and Anthony de Boer in the scary devil monastery
 
S

Sidney Cadot

CBFalconer said:
[...] C can largely implement Java, but not the converse.

To me, that's a rather aenigmatic statement.

If there is to be any comparison between the inherent expressive power
between standard Java and standard C, I'd personally select Java as the
more powerful one, if only because it has a standard library that covers
many areas of application (GUI, networking, ...) where the C standard
is silent.

Now don't get me wrong: I don't like Java all that much for a variety of
reasons, but still your statement is puzzling. Would you care to elaborate?

Best regards,

Sidney
 
E

E. Robert Tisdale

Dave said:
It would be rather beyond the scope of a student project
but I would expect that
a sufficiently enthusiastic (or masochistic) C programmer
would be able to implement a Java compiler and JVM entirely in C

See The Sable VM Project:

http://www.sablevm.org/
(though not the entire Java class library
but even there the parts that don't have equivalents in C
could be faked in C or passed on to platform-specific extensions).
Except for the aforementioned bits of the class library
that aren't found in C, it would also be possible to write
a Java-to-C compiler that outputs standard C.

Java bytecode to C:

http://compilers.iecc.com/comparch/article/97-01-051
Except for the aforementioned bits of the class library
that aren't found in C, it would also be possible to write
a Java-to-C compiler that outputs standard C.
I don't know why anyone would bother,
and it would have a few Rather Ugly bits
in both the translator and the generated C
(for example, exception handling), but it could be done[1].)

As far as the converse goes, it would be equally possible for a
sufficiently enthusiastic (or masochistic) Java programmer to implement
a C virtual machine and a compiler that targeted that CVM, but the JVM
restricts some operations vital to C (such as inspecting any data memory
as a bag of unsigned char) and that would make a C-to-Java translator
Highly Nontrivial, probably to the point of being impossible.
 
S

Sidney Cadot

Dave said:
Peter Pichler said:
So far so good...



I find it hard to believe.


It would be rather beyond the scope of a student project, but I would
expect that a sufficiently enthusiastic (or masochistic) C programmer
would be able to implement a Java compiler and JVM entirely in C
(though not the entire Java class library, but even there the parts
that don't have equivalents in C could be faked in C or passed on to
platform-specific extensions).

Except for the aforementioned bits of the class library that aren't
found in C, it would also be possible to write a Java-to-C compiler that
outputs standard C. (I don't know why anyone would bother, and it would
have a few Rather Ugly bits in both the translator and the generated C
(f'rexample, exception handling), but it could be done[1].)

Back in university I used to be involved in a (small part of a) project
that comes very close to what you describe, and your remark about
exception handling is right on the mark; so much in fact that back then
it was decided to target C++ instead of C to be able to piggyback on
C++'s exception handling. Funny thing: the compiler had no trouble
rewriting classes (including polymorphism, etc.) to C; only exception
handling was, well, exceptional.

Surely, the compiler never was fully compliant, but that wasn't the
point of the exercise (in fact, compliance at one point was /better/
than Sun's compiler). This compiler was needed for experimenting with
constructs for high-performance parallel computing.

(For those interested: this compiler can be found at
http://pds.twi.tudelft.nl/timber/spar/)
As far as the converse goes, it would be equally possible for a
sufficiently enthusiastic (or masochistic) Java programmer to implement
a C virtual machine and a compiler that targeted that CVM, but the JVM
restricts some operations vital to C (such as inspecting any data memory
as a bag of unsigned char) and that would make a C-to-Java translator
Highly Nontrivial, probably to the point of being impossible.

Well, this is just saying that both are Turing-complete, basically. By
the same token you can say that Prolog can be implemented in COBOL and
vice versa. I guess it would be fair to say that implementing C in Java
would have to involve some sort of simulation of 'untyped' memory, for
which Java doesn't have an equivalent.

Best regards,

Sidney
 
C

CBFalconer

Arthur J. O'Dwyer said:
.... snip ...


Yes and no. Yes, 'struct' is how a C programmer creates a new
data type, most often. Structs can have data members, but no
member functions (or "methods").

Pointers to functions can implement "methods", and be stored
within a struct. The usage is just somewhat different. What he
may miss most is overloading.

typedef int (*addp) (int, int);
typedef struct foo {
int a, b;
addp add;
} foo, *foop;

int addarith(int a, int b) {return a + b;}
int addlogic(int a, int b) {return a ^ b;)

foop makefoo(addp how, int av, int bv)
{
foop f;

if (f = malloc(sizeof *f)) {
f^.a = av;
f^.b = bv;
f^.add = how;
}
return f;
}

and now we can create foos that can add other foos in ways
specific to that foo.

foop fap = makefoo(addarith, 1, 1);
foop fbp = makefoo(addlogic, 1, 1);
foo fooresult;

foo addfoos(foop fa, foop fb)
{
foo fn;

fn = *fa;
fn->a = fa->add(fa->a, fb->a);
fn->b = fa->add(fa->b, fb->b);
return fn;
}

or something like that, assuming I have made no gross errors.
Results will be different between "fooresult = addfoos(fap, fbp)"
and "fooresult = addfoos(fbp, fap)".
 
B

Buck Rogers

You are already there. Buy K&R if you don't already have it.

I strongly advise against buying K&R if you are a beginner. I've bought it,
and now it's sitting idle on my shelf - it is NOT for a beginner, and will
NOT teach you C. It should be used for reference.

Luckily I've got 2 copies of Teach Yourself C in 21 days(4th & 6th
edition).
You can't learn C in 21 days. I am taking up to 2-3 days to finish each
chapter,
I sometimes take 2 days just to complete a single excersise at the end of
a
chapter, the sense of achievement is well worth the time!. But that's just
me.
Once I've finished this book, I will attack K&R with vigour!

I think TYC 21 Days is a fantastic introduction to C programming, even
though
a full 1/3 is devoted to C++, java & C#. This really annoys me, because I
am
in Australia, and computer books are at least double the US price( I paid
$85
for it, and 1/3 of it is of no use to me!).

Good luck.

Buck.
 
B

Buck Rogers

Fair enough.
C is a little bit `closer to the metal' as it were; some find it more
difficult, some find it easier. YMMV. ;-)

Here's a tip, Artie. When you use abbreviations, a percentage of the
readers
will have absolutely no idea what it stands for. I am confused, what does
YMMV mean? Your something something view??

Buck. :)
 
A

Artie Gold

Buck said:
Here's a tip, Artie. When you use abbreviations, a percentage of the
readers
will have absolutely no idea what it stands for. I am confused, what does
YMMV mean? Your something something view??

Buck. :)
<OT>
Standard jargon: `Your mileage may vary'.

See http://info.astrian.net/jargon/.
</OT>

,,,and next time, STFW! ;-) ;-) ;-)
(I hope I added enough winking smileys.)

HTH,
--ag
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,577
Members
45,052
Latest member
LucyCarper

Latest Threads

Top