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

Comma in C and C++ 

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

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

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  

A 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 the below statement, f1() and f2() can // be called in any order.
/* 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());

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;
}

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

Program 2:

#include <stdio.h>
int main()
{
    int x = 10;
    int y = (x++, ++x);
    printf("%d", y);
    getchar();
    return 0;
}

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

// 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;
}

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

3. Comma operator in place of a semicolon 

We know that in C and C++, every statement is terminated with a semicolon, but the comma operator is also used to terminate the statement after satisfying the following rules.

(i) The variable declaration statements must be terminated with a semicolon.

(ii) The statements after the declaration statement can be terminated by the comma operator.

(iii) The last statement of the program must be terminated by a semicolon.

Example:

C++

#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:

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

Comma operator questions

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, a comma is used in two contexts: (1) A separator (2) An Operator.
A comma works just as a separator in Program 1, and we get a compilation error in this program.
Comma works as an operator in Program 2. The precedence of the comma operator is the least in the operator precedence table. So the assignment operator takes precedence over the 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

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

Using the result of the comma operator as an l-value is not valid in C. But in C++, the result of the comma operator can be used as l-value if the right operand of the comma operator is an 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 a 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;
}

Output:

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

Sizeof() operator in C

Sizeof() is a much-used operator in 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, and it 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, unions, etc.

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

1. When the 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 allocated to those 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:

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

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

2. When the operand is an expression.

When sizeof() is used with the expression, it returns the 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:

Operators in C- 2 | Programming and Data Structures - Computer Science Engineering (CSE)As we know from the first case, the size of int and double is 4 and 8, respectively; a is an 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 (). Let's 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 the number of elements in an array.
Sizeof can be used to calculate the 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:

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

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 may either 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:
Operators in C- 2 | Programming and Data Structures - Computer Science Engineering (CSE)

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;
}

Output:

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

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++ (and maybe 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 a runtime error when pTemp is NULL.
It is mandatory to follow the order. In fact, it helps in generating efficient code. When the pointer pTemp is NULL, the second part will not be evaluated since the outcome of the AND (&&) expression is guaranteed to be 0.

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)
158 docs|31 tests

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.
Related Searches

Summary

,

Exam

,

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

,

video lectures

,

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

,

Viva Questions

,

MCQs

,

study material

,

Objective type Questions

,

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

,

Extra Questions

,

Previous Year Questions with Solutions

,

pdf

,

ppt

,

mock tests for examination

,

Semester Notes

,

shortcuts and tricks

,

past year papers

,

Sample Paper

,

practice quizzes

,

Important questions

,

Free

;