Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between "3" and '3' in C

Tags:

c

I tried to run the following program in C and got some output. Can you help me out why???

#include<stdio.h>

int main()
{
  char x='A';
  printf("%d%d%d",sizeof("3"),sizeof('3'),sizeof(3));
  return 0;
}

The output received is 2 4 4 using gcc in ubuntu 11.04 32 bit.

Similarly in other program:-

#include<stdio.h>

int main()
{
  char x='A';
  printf("%d%d",sizeof('A'),sizeof(x));
  return 0;
}

The output received is 4 1 using GCC in ubuntu 11.04 32 bit.

Can you help me out why the output is this way???

like image 455
Rahul Avatar asked Oct 06 '11 18:10

Rahul


People also ask

What is the difference between C and C ==?

While C and C++ may sound similar, their features and usage differ. C is a procedural programming language and does not support objects and classes. C++ is an enhanced version of C programming with object-oriented programming support. Let us discuss C and C++ programming languages and the difference between C and C++.

What does the modulus do in C?

The modulus operator is added in the arithmetic operators in C, and it works between two available operands. It divides the given numerator by the denominator to find a result. In simpler words, it produces a remainder for the integer division. Thus, the remainder is also always an integer number only.

What means & in C?

& in C is only an operator, it yields the address (or pointer to) of an object. It cannot be used in a declaration. In C++ it is a type qualifier for a reference which is similar to a pointer but has more restrictive behaviour and is therefore often safer.


1 Answers

In C, char literals are of integer type, so sizeof('3') == sizeof(int). See this C FAQ for details.

This is one of the areas where C and C++ differ (in C++ sizeof('3') is 1).

Actually, correcting my previous assertion, sizeof("3") will yield 2 because "3" is treated as a 2-element character array.

6.3.2.1/3

Except when it is the operand of the sizeof operator or the unary & operator, or is a string literal used to initialize an array, an expression that has type ‘‘array of type’’ is converted to an expression with type ‘‘pointer to type’’ that points to the initial element of the array object and is not an lvalue.

like image 123
cnicutar Avatar answered Nov 09 '22 01:11

cnicutar