Operators in C- 2 | Programming and Data Structures - Computer Science Engineering (CSE) PDF Download

Comma in C and C++

In C and C++, comma (, ) can be used in two contexts: 

  1. Comma as an operator 
    The comma operator (represented by the token, ) is a binary operator that evaluates its first operand and discards the result, it then evaluates the second operand and returns this value (and type). The comma operator has the lowest precedence of any C operator, and acts as a sequence point.
    C
    /* comma as an operator */
    int i = (5, 10); /* 10 is assigned to i*/
    int j = (f1(), f2()); /* f1() is called (evaluated) first followed by f2().
                          The returned value of f2() is assigned to j */
  2. Comma as a separator 
    Comma acts as a separator when used with function calls and definitions, function like macros, variable declarations, enum declarations, and similar constructs.
    C
    /* comma as a separator */
    int a = 1, b = 2;
    void fun(x, y);
    The use of comma as a separator should not be confused with the use as an operator. For example, in below statement, f1() and f2() can be called in any order.
    C
    /* Comma acts as a separator here and doesn't enforce any sequence.
        Therefore, either f1() or f2() can be called first */
    void fun(f1(), f2());
    See this for C vs C++ differences of using comma operator.
    You can try below programs to check your understanding of comma in C.
    C
    // Program 1
    #include <stdio.h>
    int main()
    {
        int x = 10;
        int y = 15;
        printf("%d", (x, y));
        getchar();
        return 0;
    }
    C
    // Program 2:  
    #include <stdio.h>
    int main()
    {
        int x = 10;
        int y = (x++, ++x);
        printf("%d", y);
        getchar();
        return 0;
    }
    C
    // Program 3: 
    #include <stdio.h>
    int main()
    {
        int x = 10, y;
        // The following is equivalent
        // to y = x + 2 and x += 3,
        // with two printings
        y = (x++,
             printf("x = %d\n", x),
             ++x,
             printf("x = %d\n", x),
             x++);
        // Note that last expression is evaluated
        // but side effect is not updated to y
        printf("y = %d\n", y);
        printf("x = %d\n", x);
        return 0;
    }
    C++
    #include <iostream>
    using namespace std;
    int main()
    {
        int a = 5;
        a = 2, 3, 4;
        cout << a;
        return 0;
    }
  3. Comma operator in place of a semicolon 
    We know that in C and C++, every statement is terminated with a semicolon but comma operator also used to terminate the statement after satisfying the following rules.
    (i) The variable declaration statements must be terminated with semicolon.
    (ii) The statements after declaration statement can be terminated by comma operator.
    (iii) The last statement of the program must be terminated by semicolon.
    Examples:
    CPP
    #include <iostream>
    using namespace std;
    int main()
    {
        cout << "First Line\n",
            cout << "Second Line\n",
            cout << "Third Line\n",
            cout << "Last line";
        return 0;
    }
    Output:
    First Line
    Second Line
    Third Line
    Last line

Sizeof operator in C

Sizeof is a much used operator in the C or C++. It is a compile time unary operator which can be used to compute the size of its operand. The result of sizeof is of unsigned integral type which is usually denoted by size_t. sizeof can be applied to any data-type, including primitive types such as integer and floating-point types, pointer types, or compound datatypes such as Structure, union etc.

Usage: sizeof() operator is used in different way according to the operand type.

1. When operand is a Data Type.
When sizeof() is used with the data types such as int, float, char… etc it simply returns the amount of memory is allocated to that data types.
Let's see example
C
#include <stdio.h>
int main()
{
    printf("%lu\n", sizeof(char));
    printf("%lu\n", sizeof(int));
    printf("%lu\n", sizeof(float));
    printf("%lu", sizeof(double));
    return 0;
}
C++
#include <iostream>
using namespace std;
int main()
{
    cout << sizeof(char)<<"\n";
    cout << sizeof(int)<<"\n";
    cout << sizeof(float)<<"\n";
    cout << sizeof(double)<<"\n";
    return 0;
}
Output:
1
4
4
8

Note: sizeof() may give different output according to machine, we have run our program on 32 bit gcc compiler.

2. When operand is an expression.
When sizeof() is used with the expression, it returns size of the expression. Let see example

C
#include <stdio.h>
int main()
{
    int a = 0;
    double d = 10.21;
    printf("%lu", sizeof(a + d));
    return 0;
}

C++
#include <iostream>
using namespace std;
int main()
{
    int a = 0;
    double d = 10.21;
    cout << sizeof(a + d));
    return 0;
}

Output: 8
As we know from first case size of int and double is 4 and 8 respectively, a is int variable while d is a double variable. The final result will be a double, Hence the output of our program is 8 bytes.

Type of operator
sizeof() is a compile time operator. compile time refers to the time at which the source code is converted to a binary code. It doesn’t execute (run) the code inside (). Lets see an example.
C++
#include <iostream>
using namespace std;
int main() {
int y;
int x = 11;
y = sizeof(x++);
//value of x doesn't change
cout<<y<<" "<<x;// prints 4 11
}

Need of Sizeof

1. To find out number of elements in a array.
Sizeof can be used to calculate number of elements of the array automatically. Let see Example
C
#include <stdio.h>
int main()
{
    int arr[] = { 1, 2, 3, 4, 7, 98, 0, 12, 35, 99, 14 };
    printf("Number of elements:%lu ", sizeof(arr) / sizeof(arr[0]));
    return 0;
}
C++
#include <iostream>
using namespace std;
int main()
{
    int arr[] = { 1, 2, 3, 4, 7, 98,
    0, 12, 35, 99, 14 };
    cout << "Number of elements: "
    <<(sizeof(arr) / sizeof(arr[0]));
    return 0;
}

Output:
Number of elements: 11

2. To allocate a block of memory dynamically.
sizeof is greatly used in dynamic memory allocation. For example, if we want to allocate memory for which is sufficient to hold 10 integers and we don’t know the sizeof(int) in that particular machine. We can allocate with the help of sizeof.
int* ptr = (int*)malloc(10 * sizeof(int));

Operands for sizeof operator

The sizeof operator is used to return the size of its operand, in bytes. This operator always precedes its operand. The operand either may be a data-type or an expression. Let’s look at both the operands through proper examples.
1. type-name: The type-name must be specified in parentheses.
sizeof (type - name)
Let’s look at the code:

C
#include <stdio.h>
int main()
{
    printf("%lu\n", sizeof(char));
    printf("%lu\n", sizeof(int));
    printf("%lu\n", sizeof(float));
    printf("%lu", sizeof(double));
    return 0;
}

C++
#include <iostream>
using namespace std;
int main()
{
    cout << sizeof(char)<<"\n";
    cout << sizeof(int)<<"\n";
    cout << sizeof(float)<<"\n";
    cout << sizeof(double)<<"\n";
    return 0;
}

Output:
1
4
4
8

2. expression: The expression can be specified with or without the parentheses.
// First type
sizeof expression  
// Second type
sizeof(expression)
The expression is used only for getting the type of operand and not evaluation. For example, below code prints value of i as 5 and the size of i a
C
#include <stdio.h>
int main()
{
    int i = 5;
    int int_size = sizeof(i++);
    // Displaying the size of the operand
    printf("\n size of i = %d", int_size);
    // Displaying the value of the operand
    printf("\n Value of i = %d", i);
    getchar();
    return 0;
}
C++
#include <iostream>
using namespace std;
int main()
{
    int i = 5;
    int int_size = sizeof(i++);
    // Displaying the size of the operand
    cout << "\n size of i = " << int_size;
    // Displaying the value of the operand
    cout << "\n Value of i = " << i;
    return 0;
}
// This code is contributed by SHUBHAMSINGH10

Output:
size of i = 4
Value of i = 5

A comma operator question

Consider the following C programs.
// Program 1
#include<stdio.h>
int main(void)
{
    int a = 1, 2, 3;
    printf("%d", a);
    return 0;
}
The above program fails in compilation, but the following program compiles fine and prints 1.
// Program 2
#include<stdio.h>
int main(void)
{
    int a;
    a = 1, 2, 3;
    printf("%d", a);
    return 0;
}
And the following program prints 3, why?
// Program 3
#include<stdio.h>
int main(void)
{
    int a;
    a = (1, 2, 3);
    printf("%d", a);
    return 0;
}

In a C/C++ program, comma is used in two contexts: (1) A separator (2) An Operator.
Comma works just as a separator in Program 1 and we get compilation error in this program.
Comma works as an operator in Program 2. Precedence of comma operator is least in operator precedence table. So the assignment operator takes precedence over comma and the expression “a = 1, 2, 3” becomes equivalent to “(a = 1), 2, 3”. That is why we get output as 1 in the second program.
In Program 3, brackets are used so comma operator is executed first and we get the output as 3

Order of operands for logical operators

The order of operands of logical operators &&, || are important in C/C++.
In mathematics, logical AND, OR, etc… operations are commutative. The result will not change even if we swap RHS and LHS of the operator.
In C/C++ (may be in other languages as well)  even though these operators are commutative, their order is critical. For example see the following code,
// Traverse every alternative node
while( pTemp && pTemp->Next )
{
   // Jump over to next node
   pTemp = pTemp->Next->Next;
}
The first part pTemp will be evaluated against NULL and followed by pTemp->Next. If pTemp->Next is placed first, the pointer pTemp will be dereferenced and there will be runtime error when pTemp is NULL.
It is mandatory to follow the order. Infact, it helps in generating efficient code. When the pointer pTemp is NULL, the second part will not be evaluated since the outcome of AND (&&) expression is guaranteed to be 0.

Result of comma operator as l-value in C and C++

Using result of comma operator as l-value is not valid in C. But in C++, result of comma operator can be used as l-value if the right operand of the comma operator is l-value.
For example, if we compile the following program as a C++ program, then it works and prints b = 30. And if we compile the same program as C program, then it gives warning/error in compilation (Warning in Dev C++ and error in Code Blocks).
#include<stdio.h>
int main()
{
  int a = 10, b = 20;
  (a, b) = 30; // Since b is l-value, this statement is valid in C++, but not in C.
  printf("b = %d", b);
  getchar();
  return 0;
}
C++ Output:
b = 30

The document Operators in C- 2 | Programming and Data Structures - Computer Science Engineering (CSE) is a part of the Computer Science Engineering (CSE) Course Programming and Data Structures.
All you need of Computer Science Engineering (CSE) at this link: Computer Science Engineering (CSE)
119 docs|30 tests

Top Courses for Computer Science Engineering (CSE)

FAQs on Operators in C- 2 - Programming and Data Structures - Computer Science Engineering (CSE)

1. What is a comma operator in C and how is it used?
Ans. The comma operator in C is used to separate expressions within a statement. It evaluates each expression from left to right and returns the value of the rightmost expression. It is often used in for loops, function calls, and variable assignments where multiple expressions need to be evaluated in a specific order.
2. Can the comma operator be used to separate multiple variable declarations in C?
Ans. No, the comma operator cannot be used to separate multiple variable declarations in C. Each variable declaration must be written separately and cannot be combined using the comma operator. For example, instead of writing "int a, b;", each variable declaration should be written as "int a; int b;".
3. How does the comma operator affect the order of evaluation in C expressions?
Ans. The comma operator guarantees that the expressions are evaluated from left to right. This means that the leftmost expression is always evaluated first, followed by the next expression, and so on. The value of the rightmost expression is returned as the result of the comma operator.
4. Can the comma operator be used to combine logical conditions in C?
Ans. Yes, the comma operator can be used to combine logical conditions in C. However, it should be used with caution as it does not behave like other logical operators such as && and ||. The comma operator evaluates both expressions but returns the value of the rightmost expression. This means that the left expression is not used for logical evaluation and may lead to unexpected results.
5. Are there any alternatives to using the comma operator in C?
Ans. Yes, there are alternatives to using the comma operator in C. If multiple expressions need to be evaluated in a specific order, separate statements can be used instead. Additionally, for combining logical conditions, the && and || operators are more commonly used and provide clearer and more predictable behavior.
119 docs|30 tests
Download as PDF
Explore Courses for Computer Science Engineering (CSE) exam

Top Courses for Computer Science Engineering (CSE)

Signup for Free!
Signup to see your scores go up within 7 days! Learn & Practice with 1000+ FREE Notes, Videos & Tests.
10M+ students study on EduRev
Related Searches

video lectures

,

Operators in C- 2 | Programming and Data Structures - Computer Science Engineering (CSE)

,

practice quizzes

,

Exam

,

MCQs

,

Viva Questions

,

Important questions

,

study material

,

Objective type Questions

,

Sample Paper

,

mock tests for examination

,

Free

,

Operators in C- 2 | Programming and Data Structures - Computer Science Engineering (CSE)

,

Previous Year Questions with Solutions

,

Operators in C- 2 | Programming and Data Structures - Computer Science Engineering (CSE)

,

Summary

,

shortcuts and tricks

,

pdf

,

ppt

,

Extra Questions

,

Semester Notes

,

past year papers

;