Thread: comma operator

  1. #1
    Registered User
    Join Date
    Jun 2007
    Posts
    12

    comma operator

    If ...

    int a,b; is equivalent to int a; int b;
    then
    int a=3,2; should be equivalent to int a=3;int a=2;

    I am confused ..can some one tell me what is wrong there

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    Did you try to compile it to see what you get?
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Registered User
    Join Date
    Jun 2007
    Posts
    12
    Yes ..i tried to compile it ..It says " Declaration syntax error in function main"

  4. #4
    Deathray Engineer MacGyver's Avatar
    Join Date
    Mar 2007
    Posts
    3,210
    The reason being is that a comma is not an operator.

    Try this:

    Code:
    int a=3, b=2;

  5. #5
    Hurry Slowly vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,788
    comma is an operator, but compiler does not understands, that you here want an comma operator and misinterprets it as a delimiter of declaration list as in int a, b;

    so if you want to force compiler to use comma as operator - use () as in:

    int a = (2,3);
    All problems in computer science can be solved by another level of indirection,
    except for the problem of too many layers of indirection.
    – David J. Wheeler

  6. #6
    Deathray Engineer MacGyver's Avatar
    Join Date
    Mar 2007
    Posts
    3,210
    Quote Originally Posted by vart View Post
    comma is an operator, but compiler does not understands, that you here want an comma operator and misinterprets it as a delimiter of declaration list as in int a, b;

    so if you want to force compiler to use comma as operator - use () as in:

    int a = (2,3);
    That results in this:

    : In function `main':
    :5: warning: left-hand operand of comma expression has no effect
    I don't see a point to it, anyway.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Smart pointer class
    By Elysia in forum C++ Programming
    Replies: 63
    Last Post: 11-03-2007, 07:05 AM
  2. C comma operator problem
    By greenberet in forum C Programming
    Replies: 10
    Last Post: 07-22-2007, 02:47 AM
  3. Screwy Linker Error - VC2005
    By Tonto in forum C++ Programming
    Replies: 5
    Last Post: 06-19-2007, 02:39 PM
  4. Comma Operator
    By doraiashok in forum C Programming
    Replies: 2
    Last Post: 12-09-2003, 08:38 AM
  5. operator overloading and dynamic memory program
    By jlmac2001 in forum C++ Programming
    Replies: 3
    Last Post: 04-06-2003, 11:51 PM