0

I have a struct defined as :

typedef struct pt {
  int x; 
  int y;   
}point;

I also have a stack push function declared as :

void push(point p);

Now whenever i wish to call this function, I can do the following :

point p = {x_value, y_value};
push(p);

I wanted to know if there is a less cumbersome workaround for this. Something which could enable me to do this in a single line. Maybe something like :

push((point){x_value, y_value});
4
  • Have you tried push((point){x_value, y_value}); to see if it works? Commented Oct 28, 2013 at 15:52
  • Yes, i get the error : expected primary-expression before '{' token Commented Oct 28, 2013 at 15:53
  • in c you have to allocate the memory. Constructors in C++ handle this. You need to create a constructor as Tilman states below. Commented Oct 28, 2013 at 15:56
  • @user1925405 You have to compile the code as C99. Commented Oct 28, 2013 at 15:58

2 Answers 2

6

Define a "constructor" function:

point make_point(int x, int y)
{
    point result = {x, y};
    return result;
}

Then

push(make_point(x, y));
Sign up to request clarification or add additional context in comments.

1 Comment

As a C developer, it's a reflex that I think: do people really not recognize that we live after 1999?
3

The syntax you thought of works out of the box in C99:

typedef struct {
    int x;
    int y;
} point;

push((point){ 42, 1337 });

What's even better, the resulting literal is an lvalue, so you can take its address in case your push() function accepts a pointer:

void push(point *p);

// ...

push(&(point){ 42, 1337 });

Demo here.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.