Folks, my professor has assigned us an assignment involving typing with arrays, pointers, and functions. Now, before you jump on my back with the whole "We aren't going to do your homework for you" thing, the answer to my question will not solve the problem. In fact, I've already taken my best guess at the answer. I am just curious to hear what you think about this.
Here is the C statement I was given:
double(*foo(double(*)(double,double[]),double))(double, ...);
Our problem involved describing the type of foo. My question is simply this: What on earth does this statement do? As far as I can read it, this is either one of the most obfuscated and unrealistic lines of code I've ever seen, or it's not actually valid C. Let me know what you think.
What you want to learn is the Clockwise Spiral Rule. Learning this will help you describe, in plain words, what any type in C is. Learn it well.
This will help a little
typedef RETURNTYPE (* POINTER_TO_FUNCTION_TYPE)(ARGTYPE1, ARGTYPE2)
C supports a type that is a pointer to function, and you can typedef one this way to simplify longer expressions based on it.
So, with this typedef, I could declare this function
POINTER_TO_FUNCTION_TYPE f(POINTER_TO_FUNCTION_TYPE g);
It's a function that takes a pointer to function and returns a pointer to a function. Without the typedef, imagine how that declaration would look.
According to my compiler (Visual Studio 2010) the statement does absolutely nothing. It compiles successfully, but there are no assembly instructions generated for it, so the debugger steps right over it. As for why it does nothing and what it really means - it would take someone with more knowledge of C than me to explain that.
I can figure out the type of foo using the clockwise/spiral rule, though - thanks, jer! It's easier if you reformat it a bit:
double
(
*foo
(
double(*)(double, double[]),
double
)
)
(double, ...);
Related
This question already has answers here:
Closed 12 years ago.
Possible Duplicates:
What makes more sense - char* string or char *string?
Pointer declarations in C++: placement of the asterisk
I've seen mixed versions of this in a lot of code. (This applies to C and C++, by the way.) People seem to declare pointers in one of two ways, and I have no idea which one is correct, of if it even matters.
The first way it to put the asterisk adjacent the type name, like so:
someType* somePtr;
The second way is to put the asterisk adjacent the name of the variable, like so:
someType *somePtr;
This has been driving me nuts for some time now. Is there any standard way of declaring pointers? Does it even matter how pointers are declared? I've used both declarations before, and I know that the compiler doesn't care which way it is. However, the fact that I've seen pointers declared in two different ways leads me to believe that there's a reason behind it. I'm curious if either method is more readable or logical in some way that I'm missing.
It's a matter of preference, and somewhat of a holy war, just like brace style.
The "C++" style
someType* somePtr;
is emphasizing the type of the pointer variable. It is saying, essentially, "the type of somePtr is pointer-to-someType".
The "C" style
someType *somePtr;
is emphasizing the type of the pointed-to data. It is saying, essentially, "the type of data pointed to by somePtr is someType".
They both mean the same thing, but it depends on if a given programmer's mental model when creating a pointer is "focused", so to speak, on the pointed-to data or the pointer variable.
Putting it in the middle (as someType * somePtr) is trying to avoid committing to either one.
It doesn't matter. Someone will now come along and close the question as a dupe, and someone else will show how the int* a way breaks if you declare multiple variables in the same declarations while int *a better reflects the syntactical structure of the code, and another one will show that Stroustrup prefers the int* a way and keeps the type together on the left side.
Many opinions, but no "right" way here.
It doesn't matter, it is personal preference.
Some people like to keep the type together:
int* p;
Other people say that it should go next to the variable because of the following:
int *p, x;//declare 1 int pointer and 1 int
int *p, *x;//declare 2 int pointers.
Over time you will just overlook this and accept both variations.
The difference arose because C++ added a stronger type system on top of C.
C style
A C programmer usually thinks in terms of "values," so
int *pValue;
reads "the dereference of pValue is an int".
C++ style
Whereas a C++ programmer thinks in "types" so
int* pValue;
reads "the type of pValue is pointer to int".
The compiler sees no difference at all of course. However you will find that it is the C programmers who insist on "value semantics" when programming in C++.
I think putting the asterisk adjacent to the name of the variable is clearer.
You might mistakenly declare someType* one, two; thinking that they are both pointers but only the variable one is a pointer; two is just a someType. Declaring as someType *one, *two avoids this problem.
Every single way I've seen ever is
TheType *myPointer
because you are declaring a POINTER of type TheType. Similar declaring
TheType myVar
would be declaring an instance variable of type TheType.
Also you can then clearly do this and have it easily readable
TheType myVar, *myPointer;
I'm looking for the simpliest way, how to determine return type, arguments and function name from c header file written under C99.
it's my school project, which have to be written in Perl without any libs. So i got a few options, i can use the regular expression, but it's not applicable to the hardest function like folowing:
int * (* func(int * arg[]))();
the return type should be "int * (* )()" and argument is "int * []".
Second way is to use grammar and parse it, but i think, that this is not the right way.
My buddy told me about an existing algorithm which can do it. But he doesn't remember name, or where he saw him. The algorithm was quite simple. Something like: Find first end parenthesis, everything between this end parenthesis and the first-match previous start parenthesis is arguments...
Does anyone have some idea what am I looking for?
Look at the magic decoder ring for C declarations
If you can obtain The C Programming Language by Kernighan and Ritchie. Not only is it the C bible, but in chapter 5 they present code to parse C declarations. You can look there to see how they do it and quite possibly adapt their approach (chapter 5, section 12).
You simply have to build a parser for that kind of problem. Usually the top-down approach (e.g. a recursive descent) would do it for this kind of job. Fortunately top-down parsers are more or less straight forward to implement.
The only hard bit in C like languages is, that these languages are usually at least LL1 (1 token look ahead) or even worse LL2 or more. So sometimes you have to peek a few tokens in advance to find out whether it's a function declaration or a function call for example.
We are all familiar with working of sizeof operator in C language. I am trying to make a similar working function that will absorb any kind of datatype and return me its size.
Can somebody tell me how to make such a similar function in "C".
int myOwnSizeOf(/*what would be parameter type?*/)
{
//and what about the definition?
}
Thanks
You can't do that with a function. That's why sizeof is an operator built into the language, not a library function. It's magic.
You could do
#define myOwnSizeOf(x) (sizeof(x))
but I don't really see the point.
Since a function is evaluated at runtime, it can never consume a datatype but only objects. That's why sizeof is a built in operator.
You might get it to work for this limited case in C++ with a template function. But in C your only possibilities to consume an object of any datatype are either void pointers or macros. But the former won't work, of course, as it looses any type information and the latter was already suggested by aschepler and as he noted, it won't buy you anything (and it isn't a function, anyway).
A function can't do it, but a macro can, if you don't mind throwing in a little technical UB that can't/won't really matter:
#define mysizeof(T) (size_t)((char *)((T*)0+1)-(char *)0)
If you replaced 0 with the address of a static-storage-duration object larger than any other object you'd ever try to take the size of, the UB would go away.
Edit: Note that this is for types T; a version for variables is much easier:
#define mysizeof(v) (size_t)((char *)(&v+1)-(char *)&v)
I have been implementing a user threads library as part of my assignment.
I didn't understand the makecontext function:
makecontext(&(mainthread->threadctx),(void(*)(void))start_funct,1,args)
What does (void(*)(void))start_funct exactly mean? And why do I have to write it this way?
Can't I just write it as
makecontext(&(mainthread->threadctx),start_funct,1,args) ?
Please be patient with me, I am not yet comfortable with pointers :)
void(*)(void) means "pointer to a function that takes no parameters and returns void".
Therefore (void(*)(void))start_funct is casting start_funct (which we can assume is some kind of function pointer)` to the above type. (There is a very useful online tool that can help you with this until you get more comfortable reading declarations).
You have to write it this way because the signature of start_funct is not void start_funct(void), so casting is required.
everyone. I actually have two questions, somewhat related.
Question #1: Why is gcc letting me declare variables after action statements? I thought the C89 standard did not allow this. (GCC Version: 4.4.3) It even happens when I explicitly use --std=c89 on the compile line. I know that most compilers implement things that are non-standard, i.e. C compilers allowing // comments, when the standard does not specify that. I'd like to learn just the standard, so that if I ever need to use just the standard, I don't snag on things like this.
Question #2: How do you cope without objects in C? I program as a hobby, and I have not yet used a language that does not have Objects (a.k.a. OO concepts?) -- I already know some C++, and I'd like to learn how to use C on it's own. Supposedly, one way is to make a POD struct and make functions similar to StructName_constructor(), StructName_doSomething(), etc. and pass the struct instance to each function - is this the 'proper' way, or am I totally off?
EDIT: Due to some minor confusion, I am defining what my second question is more clearly: I am not asking How do I use Objects in C? I am asking How do you manage without objects in C?, a.k.a. how do you accomplish things without objects, where you'd normally use objects?
In advance, thanks a lot. I've never used a language without OOP! :)
EDIT: As per request, here is an example of the variable declaration issue:
/* includes, or whatever */
int main(int argc, char *argv[]) {
int myInt = 5;
printf("myInt is %d\n", myInt);
int test = 4; /* This does not result in a compile error */
printf("Test is %d\n", test);
return 0;
}
c89 doesn't allow this, but c99 does. Although it's taken a long time to catch on, some compilers (including gcc) are finally starting to implement c99 features.
IMO, if you want to use OOP, you should probably stick to C++ or try out Objective C. Trying to reinvent OOP built on top of C again just doesn't make much sense.
If you insist on doing it anyway, yes, you can pass a pointer to a struct as an imitation of this -- but it's still not a good idea.
It does often make sense to pass (pointers to) structs around when you need to operate on a data structure. I would not, however, advise working very hard at grouping functions together and having them all take a pointer to a struct as their first parameter, just because that's how other languages happen to implement things.
If you happen to have a number of functions that all operate on/with a particular struct, and it really makes sense for them to all receive a pointer to that struct as their first parameter, that's great -- but don't feel obliged to force it just because C++ happens to do things that way.
Edit: As far as how you manage without objects: well, at least when I'm writing C, I tend to operate on individual characters more often. For what it's worth, in C++ I typically end up with a few relatively long lines of code; in C, I tend toward a lot of short lines instead.
There is more separation between the code and data, but to some extent they're still coupled anyway -- a binary tree (for example) still needs code to insert nodes, delete nodes, walk the tree, etc. Likewise, the code for those operations needs to know about the layout of the structure, and the names given to the pointers and such.
Personally, I tend more toward using a common naming convention in my C code, so (for a few examples) the pointers to subtrees in a binary tree are always just named left and right. If I use a linked list (rare) the pointer to the next node is always named next (and if it's doubly-linked, the other is prev). This helps a lot with being able to write code without having to spend a lot of time looking up a structure definition to figure out what name I used for something this time.
#Question #1: I don't know why there is no error, but you are right, variables have to be declared at the beginning of a block. Good thing is you can declare blocks anywhere you like :). E.g:
{
int some_local_var;
}
#Question #2: actually programming C without inheritance is sometimes quite annoying. but there are possibilities to have OOP to some degree. For example, look at the GTK source code and you will find some examples.
You are right, functions like the ones you have shown are common, but the constructor is commonly devided into an allocation function and an initialization function. E.G:
someStruct* someStruct_alloc() { return (someStruct*)malloc(sizeof(someStruct)); }
void someStruct_init(someStruct* this, int arg1, arg2) {...}
In some libraries, I have even seen some sort of polymorphism, where function pointers are stored within the struct (which have to be set in the initializing function, of course). This results in a C++ like API:
someStruct* str = someStruct_alloc();
someStruct_init(str);
str->someFunc(10, 20, 30);
Regarding OOP in C, have you looked at some of the topics on SO? For instance, Can you write object oriented code in C?.
I can't put my finger on an example, but I think they enforce an OO like discipline in Linux kernel programming as well.
In terms of learning how C works, as opposed to OO in C++, you might find it easier to take a short course in some other language that doesn't have an OO derivative -- say, Modula-2 (one of my favorites) or even BASIC (if you can still find a real BASIC implementation -- last time I wrote BASIC code it was with the QBASIC that came with DOS 5.0, later compiled in full Quick BASIC).
The methods you use to get things done in Modula-2 or Pascal (barring the strong typing, which protects against certain types of errors but makes it more complicated to do certain things) are exactly those used in non-OO C, and working in a language with different syntax might (probably will, IMO) make it easier to learn the concepts without your "programming reflexes" kicking in and trying to do OO operations in a nearly-familiar language.